Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib colorbar formatting

I've been python code to plot 4 figures with colorbars. Since I use Texfonts, matplotlib renders the minus sign too wide. I therefore have a written a formatting function to replace the minus sign with a hyphen. However, for some reason I can't apply the formatter to my colorbar. I am getting an error:

cb.ax.set_major_formatter(ticker.FuncFormatter(myfmt))
AttributeError: 'AxesSubplot' object has no attribute 'set_major_formatter'

So below is the portion of my code where it breaks: Do you have an idea how to force the colorbar to use my formatting function?

#!/usr/bin/env python3 

import re
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc 
from matplotlib.ticker import *
import matplotlib.ticker as ticker
import matplotlib as mpl
import matplotlib.gridspec as gridspec
from matplotlib.patches import Ellipse
from list2nparr import list2nparr
from matplotlib.ticker import ScalarFormatter 

plt.rcParams['text.usetex'] = True
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = 'cm'
plt.rcParams['font.size'] = 16
#plt.rcParams['font.weight'] = 'heavy'
plt.rcParams['axes.unicode_minus'] = False
#-----------------------------------------------------


def myfmt(x, pos=None):
  rv = format(x)
  if mpl.rcParams["text.usetex"]:
    rv = re.sub('$-$', r'\mhyphen', rv)

  return rv


fig,(ax1,ax2,ax3,ax4) = plt.subplots(nrows=4,figsize=(6,11),sharex = True, sharey=False)
data = list2nparr('radiant.txt')

lm  = data[:,14]
bet = data[:,15]
v   = data[:,16]
b   = data[:,18]
ejep = data[:,20]

fig.subplots_adjust(hspace=0.1)

cm = plt.cm.get_cmap('jet') 
sc = ax1.scatter(lm, bet, c=ejep, s=10, cmap=cm, edgecolor='none',rasterized=True)
cb=plt.colorbar(sc,ax = ax1,aspect=10)
cb.formatter.set_powerlimits((0, 0))
cb.ax.set_major_formatter(ticker.FuncFormatter(myfmt))
cb.update_ticks()
like image 889
user3578925 Avatar asked Dec 24 '15 23:12

user3578925


1 Answers

You need to specify the xaxis:

cb.ax.xaxis.set_major_formatter(plt.FuncFormatter(myfmt))

or yaxis:

cb.ax.yaxis.set_major_formatter(plt.FuncFormatter(myfmt))

when setting the formatter.

like image 199
Mike Müller Avatar answered Nov 10 '22 05:11

Mike Müller