【问题标题】:Matplotlib Colorbar Ticks Mathtext FormatMatplotlib 颜色条刻度 Mathtext 格式
【发布时间】:2020-03-28 20:59:09
【问题描述】:

标题是不言自明的,找不到如何实现它。对于轴刻度格式,类似的命令如下所示:ax.ticklabel_format(useMathText=True),这个没有问题,它可以工作。但是为了使颜色条的刻度以 MathText 格式出现,我找不到如何实现它。我试图将 useMathText=True 作为 arg 传递给 cbar.ax.tick_params()cbar = plt.colorbar() 但这没有用。

重新创建:

import numpy as np
import matplotlib.tri as mtri
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

p = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0.5, 0.5]])
e = np.array([[0, 1, 4], [3, 0, 4], [1, 2, 4], [2, 3, 4]])
t = mtri.Triangulation(p[:, 0], p[:, 1], e)
z = np.random.rand(5)

fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
ax.set_aspect('equal', 'box')
ax.set(xlim=(min(p[:, 0]), max(p[:, 0])), ylim=(min(p[:, 1]), max(p[:, 1])))
c = ax.tricontourf(t, z, 10, cmap='plasma', vmin=np.min(z), vmax=np.max(z),
                   levels=np.linspace(np.min(z), np.max(z), 100))
ax.triplot(t, color='white', lw=0.1)
ax.set_title('Title', fontsize=16)
cbar = plt.colorbar(c, cax=cax, format='%.0e', ticks=np.linspace(np.min(z), np.max(z), 3))
cbar.set_label('Colorbar title', fontsize=16)
# cbar.ax.ticklabel_format(useMathText=True)
ax.ticklabel_format(useMathText=True)
plt.show()

【问题讨论】:

  • @JohanC 是的,一堆属性错误。

标签: matplotlib plot format


【解决方案1】:

正如 Ernest 在 cmets 中所解释的,轮廓的颜色条得到 FixedFormatter,它不接受 useMathText。在我的版本中,代码没有给出错误,但正如您所指出的,也没有生成所需的输出。

因此,答案是将格式化程序更改为 ScalarFormatter,同时告诉它使用数学文本。可以通过cbar.ax.yaxis.set_major_formatter 设置垂直颜色条的格式化程序。

from matplotlib import pyplot as plt
from matplotlib import ticker
import numpy as np

plt.tricontourf(np.random.uniform(1, 10, 100), np.random.uniform(1, 10, 100), np.random.uniform(1e-6, 1e-5, 100))
cbar = plt.colorbar()
cbar.ax.yaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))
plt.show()

请让我知道它现在是否适合您。 (我的系统,现在用matplotlib 3.2.1,Windows下的Pycharm 2019.3.4。)

【讨论】:

  • 检查了版本。我试过你的例子,它奏效了。与我的情况不同的是,我使用ax.tricontourf() 来绘制数据,cbar = plt.colorbar() 是相似的,但是cbar.ax.ticklabel_format(useMathText=True) 在我的情况下会导致错误。我将发布一段我的代码。
  • 我没有投反对票,但肯定用问题回答问题是非常糟糕的风格。我想它只是告诉你这个问题不够清楚,根本不应该回答。关于实际问题,请考虑 ticklabel_format(useMathText=True) 仅适用于具有 useMathText 属性的格式化程序;和轮廓颜色条默认使用固定的格式化程序。
  • 反对票来自我。原因是在 3.1.2 和 3.2.0 中尝试了您的代码后,我得到了异常:AttributeError: 'FixedFormatter' object has no attribute 'set_useMathText' 来自 .../matplotlib/axes/_base.py 中的 axis.major.formatter.set_useMathText(useMathText) 行。一条消息AttributeError: This method only works with the ScalarFormatter 追溯到cbar.ax.ticklabel_format(useMathText=True),大概是出于欧内斯特评论中概述的原因。我认为“无法重现”的答案很有用,但前提是包含所有细节(操作系统等)
  • 如果你要更新你的答案以包括你如何执行那段代码和你的操作系统,所以它在确定它为什么对你有效而不是对我和我自己有效时更有用绝对考虑删除我的反对票。
  • @JohanC 但是在你的这个例子中,我觉得 mathtext 不起作用,它应该以 10^-5 而不是 1e-5 的格式显示数字。
猜你喜欢
  • 2016-06-14
  • 2013-09-13
  • 1970-01-01
  • 2020-08-03
  • 2017-01-22
  • 2020-02-18
  • 1970-01-01
  • 2018-10-06
  • 2020-01-05
相关资源
最近更新 更多