带有Qt5Agg后端的matplotlib返回空的ticklabels

2024-04-19 04:05:18 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码片段中,我想在绘图的所有Y轴刻度标签上附加一个百分号:

import matplotlib as mpl
import pandas as pd
from matplotlib import pyplot as plt
print mpl.__version__, mpl.get_backend()

df = pd.DataFrame({'a': [10, 40], 'b': [20, 30]})
ax = df.plot(kind='bar', title='Plot of Percentage')
plt.draw()
ax.set_yticklabels([x.get_text() + '%' for x in ax.get_yticklabels()])
ax.get_figure().savefig('test.png', bbox_inches='tight')

在python 2.7.13+matplotlib 1.5.3中,使用后端Qt5Agg,ax.get_yticklabels()返回一个空的Text对象的列表,得到以下输出图像:

enter image description here

上面的代码片段在python2.6.9+matplotlib 1.4.2+Qt4Agg后端和python2.6.6+matplotlib 1.3.1+TkAgg后端下都能正常工作。

可能与:https://github.com/matplotlib/matplotlib/issues/6103/


Tags: 代码import绘图pandasdfgetmatplotlibas
1条回答
网友
1楼 · 发布于 2024-04-19 04:05:18

在画布完全绘制之前,ticklabels不会被实际填充。由于ticklabels是由matplotlib.ticker.***Formatter决定的,所以最好的解决方案当然不是试图更改ticklabels本身,而是使用一个方便的格式化程序。在

在这里,FuncFormatter似乎是个不错的选择。在

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker

df = pd.DataFrame({'a': [10, 40], 'b': [20, 30]})
ax = df.plot(kind='bar', title='Plot of Percentage')

func = lambda x, pos: "{} %".format(x)
ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(func))
plt.show()

enter image description here

无需绘制任何内容,而且此解决方案也独立于后端。在

相关问题 更多 >