【发布时间】:2017-01-05 23:13:04
【问题描述】:
在下面的代码 sn-p 中,我想在绘图的所有 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 对象的列表,产生以下输出图像:
上述代码 sn-p 在 python 2.6.9 + matplotlib 1.4.2 + Qt4Agg 后端和 python 2.6.6 + matplotlib 1.3.1 + TkAgg 后端下正常工作。
【问题讨论】:
-
这不是最佳解决方案,但它有效。将plt.draw()改成plt.show(),关闭窗口后保存带有修改标签的图片
-
@eyllanesc:感谢内联图像。我试图用 plt.show() 替换 sivefig 行,但它似乎不起作用。还有其他我错过的环境吗?
-
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='百分比图') plt.show() ax.set_yticklabels([x.get_text() + '% ' for x in ax.get_yticklabels()]) ax.get_figure().savefig('test.png', bbox_inches='tight')
-
@eyllanesc:是的,它奏效了。非常感谢!
-
一探究竟:首先使用
ax.yaxis.get_ticklocs()从yticks 中提取数字,然后使用ax.yaxis.set_ticklabels()设置带有百分号的新刻度标签。感谢@WuSun 的贡献。
标签: python matplotlib pyqt5