matplotlib 中的日期刻度和旋转 [英] Date ticks and rotation in matplotlib
问题描述
我在尝试在 matplotlib 中旋转日期刻度时遇到问题.下面是一个小示例程序.如果我尝试在最后旋转刻度线,则刻度线不会旋转.如果我尝试按照注释崩溃"下所示旋转刻度,则 matplot lib 会崩溃.
I am having an issue trying to get my date ticks rotated in matplotlib. A small sample program is below. If I try to rotate the ticks at the end, the ticks do not get rotated. If I try to rotate the ticks as shown under the comment 'crashes', then matplot lib crashes.
仅当 x 值为日期时才会发生这种情况.如果我在调用 avail_plot
时将变量 dates
替换为变量 t
,则 xticks(rotation=70)
调用在 avail_plot
中工作得很好.
This only happens if the x-values are dates. If I replaces the variable dates
with the variable t
in the call to avail_plot
, the xticks(rotation=70)
call works just fine inside avail_plot
.
有什么想法吗?
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
def avail_plot(ax, x, y, label, lcolor):
ax.plot(x,y,'b')
ax.set_ylabel(label, rotation='horizontal', color=lcolor)
ax.get_yaxis().set_ticks([])
#crashes
#plt.xticks(rotation=70)
ax2 = ax.twinx()
ax2.plot(x, [1 for a in y], 'b')
ax2.get_yaxis().set_ticks([])
ax2.set_ylabel('testing')
f, axs = plt.subplots(2, sharex=True, sharey=True)
t = np.arange(0.01, 5, 1)
s1 = np.exp(t)
start = dt.datetime.now()
dates=[]
for val in t:
next_val = start + dt.timedelta(0,val)
dates.append(next_val)
start = next_val
avail_plot(axs[0], dates, s1, 'testing', 'green')
avail_plot(axs[1], dates, s1, 'testing2', 'red')
plt.subplots_adjust(hspace=0, bottom=0.3)
plt.yticks([0.5,],("",""))
#doesn't crash, but does not rotate the xticks
#plt.xticks(rotation=70)
plt.show()
推荐答案
如果您更喜欢非面向对象的方法,请将 plt.xticks(rotation=70)
移动到右侧 之前 两个 avail_plot
调用,例如
If you prefer a non-object-oriented approach, move plt.xticks(rotation=70)
to right before the two avail_plot
calls, eg
plt.xticks(rotation=70)
avail_plot(axs[0], dates, s1, 'testing', 'green')
avail_plot(axs[1], dates, s1, 'testing2', 'red')
这会在设置标签之前设置旋转属性.由于这里有两个轴,plt.xticks
在绘制两个图后会感到困惑.当 plt.xticks
不做任何事情时,plt.gca()
不会不给你想要修改的轴,因此作用于当前轴的 plt.xticks
将不起作用.
This sets the rotation property before setting up the labels. Since you have two axes here, plt.xticks
gets confused after you've made the two plots. At the point when plt.xticks
doesn't do anything, plt.gca()
does not give you the axes you want to modify, and so plt.xticks
, which acts on the current axes, is not going to work.
对于不使用 plt.xticks
的面向对象方法,您可以使用
For an object-oriented approach not using plt.xticks
, you can use
plt.setp( axs[1].xaxis.get_majorticklabels(), rotation=70 )
在两次 avail_plot
调用之后.这会专门设置正确轴上的旋转.
after the two avail_plot
calls. This sets the rotation on the correct axes specifically.
这篇关于matplotlib 中的日期刻度和旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!