pandas 修改熊猫图的日期刻度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45704366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:15:30  来源:igfitidea点击:

Modify date ticks for pandas plot

pythonpandasdatetimematplotlib

提问by MLhacker

Below shows a plot of simulated data, which contains the xticks that I want to modify. By default, the pd.df.plot chooses dates that are approximately 3 months apart as ticks. But what I want is each month being a tick. What is the best way to do this? What about seasonal ticks? Thank you in advance.

下面显示了模拟数据图,其中包含我要修改的 xticks。默认情况下,pd.df.plot 选择相隔大约 3 个月的日期作为刻度。但我想要的是每个月都是一个滴答声。做这个的最好方式是什么?季节性蜱虫呢?先感谢您。

enter image description here

在此处输入图片说明

回答by Serenity

First of all you have to convert pandas date objects to python date objects. This conversion is needed because of matplotlib internal date conversion functions. Then use functions from matplotlib.datesto set desired formatter and tick positions like here:

首先,您必须将 Pandas 日期对象转换为 Python 日期对象。由于 matplotlib 内部日期转换功能,需要进行此转换。然后使用函数 frommatplotlib.dates设置所需的格式化程序和刻度位置,如下所示:

import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import matplotlib.dates as mdates

# convert date objects from pandas format to python datetime
index = pd.date_range(start = "2015-07-01", end = "2017-01-01", freq = "D")
index = [pd.to_datetime(date, format='%Y-%m-%d').date() for date in index]
data = np.random.randint(1,100, size=len(index))
df = pd.DataFrame(data=data,index=index, columns=['data'])
print (df.head())

ax = df.plot()
# set monthly locator
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
# set formatter
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
# set font and rotation for date tick labels
plt.gcf().autofmt_xdate()

plt.show()

For season labels you have to construct it by yourself and then set it with plt.setpfunction (for month 02 set label winter, 04 - springetc.): plt.setp(new_labels, rotation=90, fontsize=9).

对于季节标签,您必须自己构建它,然后使用plt.setp函数进行设置(对于 02 月设置标签winter,04 -spring等): plt.setp(new_labels, rotation=90, fontsize=9).

enter image description here

在此处输入图片说明

head of df:

df负责人:

            data
2015-07-01    26
2015-07-02    33
2015-07-03    46
2015-07-04    69
2015-07-05    17

回答by zurfyx

I had a hard time trying to get @Serenity answerto work because I'm working directly with Matplotlib instead of plotting the Pandas dataset. So if you are one of these, my answer might help.

我很难让@Serenity 回答工作,因为我直接使用 Matplotlib 而不是绘制 Pandas 数据集。因此,如果您是其中之一,我的回答可能会有所帮助。

Plotting with Matplotlib.plot()

使用 Matplotlib.plot() 绘图

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Process dataset
bitcoin['Date'] = pd.to_datetime(bitcoin['Date'])
bitcoin['Open'] = pd.to_numeric(bitcoin['Open'])

# Plot
plt.figure()
plt.plot(bitcoin['Date'], bitcoin['Open'])
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=4))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.gcf().autofmt_xdate() # Rotation
plt.show()
bitcoin[['Date', 'Open']].head()

    Date        Open
0   2017-09-05  4228.29
1   2017-09-04  4591.63
2   2017-09-03  4585.27
3   2017-09-02  4901.42
4   2017-09-01  4701.76

Bitcoin price chart

比特币价格图表