matplotlib colorbar格式化

时间:2015-12-24 23:58:47

标签: python matplotlib

我一直是使用彩条绘制4个数字的python代码。由于我使用Texfonts,matplotlib使得减号太宽。因此,我有一个格式化函数,用连字符替换减号。 但是,出于某种原因,我无法将格式化程序应用于我的颜色栏。 我收到一个错误:

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

以下是我的代码中断的部分: 你知道如何强制使用我的格式化功能吗?

#!/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()

2 个答案:

答案 0 :(得分:2)

您需要指定xaxis

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

yaxis

cb.ax.yaxis.set_major_formatter(plt.FuncFormatter(myfmt))
设置格式化程序时

答案 1 :(得分:0)

我在以下帖子中找到了答案: in the following post

解决方案是,不是使用LogFormatter,而是必须将函数更改为ScalarFormatter并将\ mhyphen定义为:

plt.rcParams["text.latex.preamble"].append(r'\mathchardef\mhyphen="2D')

所以这个课程的以下定义对我有用:

class Myfmt(mpl.ticker.ScalarFormatter):
    def __call__(self, x, pos=None):
        # call the original LogFormatter
        rv =mpl.ticker.ScalarFormatter.__call__(self, x, pos)

        # check if we really use TeX
        if mpl.rcParams["text.usetex"]:
            # if we have the string ^{- there is a negative exponent
            # where the minus sign is replaced by the short hyphen
            rv = re.sub('-', r'\mhyphen', rv)

        return rv

然后我改变了界限:

cb=plt.colorbar(sc,ax = ax1,aspect=10)

cb=plt.colorbar(sc,ax = ax1,aspect=10,format=Myfmt())

我还启用了在颜色条顶部放置单个指数的行:

cb.formatter.set_powerlimits((0, 0))

感谢您帮助我找到答案!