matplotlib中的日期刻度和旋转 [英] Date ticks and rotation in matplotlib

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

问题描述

我在尝试在matplotlib中旋转日期刻度时遇到问题.下面是一个小示例程序.如果我尝试最后旋转刻度线,则刻度线不会旋转.如果我尝试如注释"crashes"下所示旋转刻度线,则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屋!

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