Matplotlib中x轴标签的频率和旋转 [英] Frequency and rotation of x-axis labels in Matplotlib

查看:169
本文介绍了Matplotlib中x轴标签的频率和旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面编写了一个简单的脚本,以使用matplotlib生成图形.我想将x-tick频率从每月增加到每周,并旋转标签.我不确定从x轴频率开始.我的旋转线产生错误:TypeError: set_xticks() got an unexpected keyword argument 'rotation'.对于旋转,我不希望使用 plt.xticks(rotation=70),因为我最终可能会构建多个子图,其中一些应该有一个旋转轴,一些不应该.

I wrote a simple script below to generate a graph with matplotlib. I would like to increase the x-tick frequency from monthly to weekly and rotate the labels. I'm not sure where to start with the x-axis frequency. My rotation line yields an error: TypeError: set_xticks() got an unexpected keyword argument 'rotation'. For the rotation, I'd prefer not to use plt.xticks(rotation=70) as I may eventually build in multiple subplots, some of which should have a rotated axis and some which should not.

import datetime
import matplotlib
import matplotlib.pyplot as plt
from datetime import date, datetime, timedelta

def date_increments(start, end, delta):
    curr = start
    while curr <= end:
        yield curr
        curr += delta

x_values = [[res] for res in date_increments(date(2014, 1, 1), date(2014, 12, 31), timedelta(days=1))]
print len(x_values)
y_values = [x**2 for x in range(len(x_values))]
print len(y_values)
fig = plt.figure()

ax = fig.add_subplot(111)
ax.plot(x_values, y_values)
ax.set_xticks(rotation=70)
plt.show()

推荐答案

查看 matplotlib.dates,尤其是 这个例子.

滴答频率

你可能想要做这样的事情:

You will probably want to do something like this:

from matplotlib.dates import DateFormatter, DayLocator, MonthLocator
days = DayLocator()
months = MonthLocator()

months_f = DateFormatter('%m')

ax.xaxis.set_major_locator(months)
ax.xaxis.set_minor_locator(days)
ax.xaxis.set_major_formatter(months_f)

ax.xaxis_date()

这会将天绘制为次要刻度,将月份绘制为主要刻度,并标有月份编号.

This will plot days as minor ticks and months as major ticks, labelled with the month number.

标签旋转

您可以使用 plt.setp() 单独更改轴:

You can use plt.setp() to change axes individually:

plt.setp(ax.get_xticklabels(), rotation=70, horizontalalignment='right')

希望这会有所帮助.

这篇关于Matplotlib中x轴标签的频率和旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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