Matplotlib颜色条格式化

8

我一直在使用Python代码绘制带有色条的4个图形。由于我使用Texfonts,matplotlib渲染负号过宽。因此,我编写了一个格式化函数来将负号替换为连字符。然而,由于某种原因,我无法将该格式化程序应用于我的色条上。我遇到了一个错误:

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

以下是代码中断的部分: 你有什么想法可以强制colorbar使用我的格式化函数吗?
#!/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个回答

5
您需要指定xaxis
cb.ax.xaxis.set_major_formatter(plt.FuncFormatter(myfmt))

或者 y轴:
cb.ax.yaxis.set_major_formatter(plt.FuncFormatter(myfmt))

设置格式化程序时,需要注意以下几点。

我在代码中将行修改为: cb.ax.yaxis.set_major_formatter(ticker.FuncFormatter(myfmt))现在它顺利运行没有任何错误,但我注意到它根本没有调用函数。我在我的函数中加了一行“print(rv)”,但它并没有打印出任何东西,负号仍然太大了。 - user3578925
plt.FuncFormatter(myfmt)ticker.FuncFormatter(myfmt) 对我来说都可以使用。请确保您提交的是正确的函数。 - Mike Müller
我将代码改为:cb.ax.yaxis.set_major_formatter(plt.FuncFormatter(myfmt)),但仍然没有效果。该函数似乎根本没有被调用,因为它没有打印任何内容。此外,图中的负号仍然没有改变。 - user3578925
我想澄清一下,如果将行: cb=plt.colorbar(sc,ax = ax1,aspect=10) 更改为 cb=plt.colorbar(sc,ax = ax1,aspect=10,format=ticker.FuncFormatter(myfmt)) 并禁用行 #cb.formatter.set_powerlimits((0, 0)) 它可以工作-将减号更改为连字符,但是我失去了指数放置在色条顶部的功能。但是,如果启用行 cb.formatter.set_powerlimits((0, 0)) 我会收到以下错误: cb.formatter.set_powerlimits((0, 0)) AttributeError: 'FuncFormatter'对象没有属性'set_powerlimits' - user3578925

0
我在以下帖子中找到了答案:在以下帖子中 解决方法是,不要使用 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)

to

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

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

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

感谢您帮助我找到答案!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接