旋转 xticks 导致刻度部分隐藏在 matplotlib 中 [英] rotating xticks causes the ticks partially hidden in matplotlib

查看:138
本文介绍了旋转 xticks 导致刻度部分隐藏在 matplotlib 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a plot with names on x axis and time values(minutes) on y axis.The names on x axis are like

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

其中 y 值为 5、1、1 等.我将 xlabel 设为类别",将 ylabel 设为持续时间(以分钟为单位)".

where as the y values are 5,1,1 etc.I have given xlabel as 'categories' and ylabel as 'durations in minutes'.

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

Since the xticks were strings of some length,I decided to rotate them by 90 to avoid overlapping.Now ,the ticks are partially hidden and the xlabel has disappeared. Is there some way I can make the whole plot accommodate everything..?

谢谢

标记

这里是代码片段

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")

推荐答案

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

One good option is to rotate the tick labels.

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

In your specific case, you might find it convenient to use figure.autofmt_xdate() (Which will rotate the x-axis labels among other things).

或者,您可以执行 plt.setp(plt.xticks()[1], rotation=30) (或执行相同操作的各种其他方式).

Alternatively, you could do plt.setp(plt.xticks()[1], rotation=30) (or various other ways of doing the same thing).

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

Also, as a several year later edit, with recent versions of matplotlib, you can call fig.tight_layout() to resize things to fit the labels inside the figure, as @elgehelge notes below.

这篇关于旋转 xticks 导致刻度部分隐藏在 matplotlib 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆