【问题标题】:matplotlib with Qt5Agg backend returns empty ticklabels带有 Qt5Agg 后端的 matplotlib 返回空的刻度标签
【发布时间】: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 后端下正常工作。

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

【问题讨论】:

  • 这不是最佳解决方案,但它有效。将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


【解决方案1】:

直到画布完全绘制,刻度标签才真正被填充。由于刻度标签由matplotlib.ticker.***Formatter 确定,因此最好的解决方案当然不是尝试更改刻度标签本身,而是使用方便的格式化程序。

这里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()

不需要绘制任何东西,这个解决方案也独立于后端。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 2017-05-13
    • 1970-01-01
    • 2019-07-10
    • 2014-06-30
    • 1970-01-01
    相关资源
    最近更新 更多