带有 Qt5Agg 后端的 matplotlib 返回空刻度标签 [英] matplotlib with Qt5Agg backend returns empty ticklabels
问题描述
在下面的代码片段中,我想在绘图的所有Y轴刻度标签上附加一个百分号:
将matplotlib导入为mpl将熊猫作为pd导入从 matplotlib 导入 pyplot 作为 plt打印mpl .__ version__,mpl.get_backend()df = pd.DataFrame({'a': [10, 40], 'b': [20, 30]})ax = df.plot(种类='bar',title ='百分比图')plt.draw()ax.set_yticklabels([x.get_yticklabels()中的x的'x.get_text()+'%')ax.get_figure().savefig('test.png', bbox_inches='tight')
在 python 2.7.13 + matplotlib 1.5.3 中,使用后端 Qt5Agg,ax.get_yticklabels()
返回空的 Text
对象列表,结果如下输出图片:
以上代码段在python 2.6.9 + matplotlib 1.4.2 + Qt4Agg后端以及python 2.6.6 + matplotlib 1.3.1 + TkAgg后端下均能正常工作.
可能与:
无需绘制任何东西,该解决方案也独立于后端.
In the following code snippet, I want to append a percentage sign to all Y axis tick labels of a plot:
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')
In python 2.7.13 + matplotlib 1.5.3, using backend Qt5Agg, ax.get_yticklabels()
returns a list of empty Text
objects, resulting in the following output image:
The above code snippet works correctly under python 2.6.9 + matplotlib 1.4.2 + Qt4Agg backend and under python 2.6.6 + matplotlib 1.3.1 + TkAgg backend.
Possibly related to: https://github.com/matplotlib/matplotlib/issues/6103/
The ticklabels are not actually filled until the canvas is completely drawn. Since the ticklabels are determined by a matplotlib.ticker.***Formatter
, the best solution is of course not trying to change the ticklabels themselves but to use a convenient Formatter.
Here a FuncFormatter
seems a good choice.
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()
There is no need to draw anything and this solution is also independent on backends.
这篇关于带有 Qt5Agg 后端的 matplotlib 返回空刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!