【问题标题】:rotating xticks causes the ticks partially hidden in matplotlib旋转 xticks 导致刻度部分隐藏在 matplotlib 中
【发布时间】:2011-10-06 01:01:11
【问题描述】:

我正在创建一个绘图,其中 x 轴上的名称和 y 轴上的时间值(分钟)。x 轴上的名称就像

 ['cooking']18:15:27 ,['study']18:09:19,['travel']18:21:34` etc ..

其中 y 值为 5、1、1 等。我将 xlabel 指定为“类别”,将 ylabel 指定为“持续时间(以分钟为单位)”。

由于 xticks 是一些长度的字符串,我决定将它们旋转 90 以避免重叠。现在,刻度被部分隐藏并且 xlabel 消失了。 有什么办法可以让整个情节适应一切..?

谢谢

标记

这里是代码sn-p

import matplotlib.pyplot as plt
...
figure = plt.figure()
barwidth = 0.25
ystep = 10
plt.grid(True)
plt.xlabel('categories')
plt.ylabel('durations in  minutes')
plt.title('durations for categories-created at :'+now)
plt.bar(xdata, ydata, width=barwidth,align='center')
plt.xticks(xdata,catnames,rotation=90)
plt.yticks(range(0,maxduration+ystep,ystep))
plt.xlim([min(xdata) - 0.5, max(xdata) + 0.5])
plt.ylim(0,max(ydata)+ystep)
figure.savefig("myplot.png",format="png")

【问题讨论】:

    标签: python matplotlib rotation label


    【解决方案1】:

    一个不错的选择是旋转刻度标签。

    在您的特定情况下,您可能会发现使用 figure.autofmt_xdate() 很方便(这将旋转 x 轴标签等)。

    或者,您可以使用plt.setp(plt.xticks()[1], rotation=30)(或其他各种方式来做同样的事情)。

    此外,作为几年后的编辑,使用最新版本的 matplotlib,您可以调用 fig.tight_layout() 来调整大小以适应图中的标签,如下面的@elgehelge 所述。

    【讨论】:

    • 非常感谢..figure.autofmt_xdate 在省略旋转值时会有所帮助..我刚刚接触了 Sandro Tosi 的书..我想会帮助我了解更多信息
    【解决方案2】:
    plt.tight_layout()
    

    但一定要在plt.plot()plt.bar()

    之后添加这个命令

    【讨论】:

    • 谢谢。完美运行!
    【解决方案3】:

    保存时设置边界框也会显示标签:

    figure.savefig('myplot.png', bbox_inches='tight')
    

    【讨论】:

      猜你喜欢
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 2015-09-20
      相关资源
      最近更新 更多