问题描述
标题是不言自明的,找不到如何实现.对于轴刻度格式,类似的命令如下所示:ax.ticklabel_format(useMathText=True)
,此命令没有问题,它可以工作.但是,为了使颜色条的刻度线以MathText格式显示,我找不到如何实现它.我试图将useMathText=True
作为arg传递给cbar.ax.tick_params()
和cbar = plt.colorbar()
,但这没有用.
The title is self explanatory, could not find how to implement it. For the axis ticks format similar command looks like this: ax.ticklabel_format(useMathText=True)
, there is no problem with this one, it works. But for the colorbar's ticks to make them appear in the MathText format I could not find how to implement it. I have tried to pass the useMathText=True
as an arg into the cbar.ax.tick_params()
and cbar = plt.colorbar()
but that did not work.
重新创建:
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()
推荐答案
如欧内斯特(Ernest)的评论所述,轮廓的颜色栏为FixedFormatter
,不接受useMathText
.在我的版本中,代码没有给出错误,但是正如您所指出的那样,也没有生成所需的输出.
As explained in the comments by Ernest, the colorbar for a contour gets a FixedFormatter
, which doesn't accept useMathText
. In my version, the code didn't give an error, but as you pointed out, also didn't generate the desired output.
因此,答案是将格式化程序更改为ScalarFormatter,同时告诉它使用数学文本.可以通过cbar.ax.yaxis.set_major_formatter
设置垂直颜色栏的格式器.
So, the answer is to change the formatter to a ScalarFormatter, and at the same time tell it to use math text. The formatter for a vertical colorbar can be set via 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.)
Please let me know whether it now works for you. (My system, now with matplotlib 3.2.1, Pycharm 2019.3.4 under Windows.)
这篇关于Matplotlib Colorbar标记Mathtext格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!