简体   繁体   English

如何使用matplotlib在没有overlapp的情况下调整月份?

[英]How to adjust month on axis without overlapp using matplotlib?

I'm trying to plot the following data with matplotlib. 我正在尝试使用matplotlib绘制以下数据。

      Month    A     B       C
0   2014/06    41    17      3
1   2014/07    48    11      7
2   2014/08    58    20      4
3   2014/09    43    16      6
4   2014/10    73    13      7
5   2014/11    69    22     16
6   2014/12    65    34      9
7   2015/01    69    27     12

I'm having the following code: 我有以下代码:

x = np.arange(len(df["Month"].values))
y1=df["A"].values.astype(int)
y2=df["B"].values.astype(int)
y3=df["C"].values.astype(int)

my_xticks = df["Month"].values
plt.xticks(x, my_xticks)
plt.plot(x,y1)
plt.plot(x,y2)
plt.plot(x,y3)
plt.show()

The problem is the months are overlapping each other on x-axis. 问题是月份在x轴上彼此重叠。 Can I make this automatically adjusted by Python. 我可以通过Python自动调整它吗? Not only I need to rotate, but also automatically ignore some months. 我不仅需要轮换,而且还自动忽略了几个月。 Otherwise, it's too crowded. 否则,它太拥挤了。

Matplotlib has a function which can automatically format your x axis when they are dates - autofmt_xdate . Matplotlib具有可以自动将x轴设置为日期的格式的功能autofmt_xdate This automatically rotates the labels, and positions the ticks. 这将自动旋转标签,并放置刻度。 They can be changed from the defaults by passing arguments to this function. 可以通过将参数传递给此函数来将其从默认值更改。 They can also, of course, be changed manually, but this requires (slightly) more effort. 当然,也可以手动更改它们,但这需要(略)多的努力。

You can easily reduce the number of dates shown be sampling every 2nd element of the list, using the slice notation [::2] 您可以使用切片符号[::2]轻松减少列表中每个第二个元素采样显示的日期数量

# Code here that creates a list of dates called list_of_dates...
print (list_of_dates)
# ['2016-08', '2016-09', '2016-10', '2016-11', '2016-12', '2017-01',
# '2017-02', '2017-03', '2017-04', '2017-05', '2017-06', '2017-07',
# '2017-08', '2017-09', '2017-10', '2017-11', '2017-12', '2018-01']
x = np.arange(0, len(list_of_dates), 1)

plt.xticks(x[::2], list_of_dates[::2])
plt.plot(x, np.random.randn(len(list_of_dates)))

# plt.gcf() means "get current figure"
plt.gcf().autofmt_xdate(ha="center")

plt.show()

Which gives: 这使:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM