在 Pandas 绘图创建时跳过 gcf().autofmt_xdate()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24337753/
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-13 22:10:53  来源:igfitidea点击:

Skip gcf().autofmt_xdate() at pandas plot creation

pythonmatplotlibplotpandas

提问by alejo0317

I'm trying to plot multiple time series using a pandas dataframe. The dataframe contains more than 100 registers.

我正在尝试使用 Pandas 数据框绘制多个时间序列。数据帧包含 100 多个寄存器。

From the panda's documentation I've read that when pandas.df.plot() is executed this is also executed with gcf().autofmt_xdate(). I want to put my custom datetime format but when I tried my custom date format is overlapped over the date given by default by pandas plot. ?Is there a way to skip gcf().autofmt_xdate() on plot creation? ?How can i provide to panda a custom datetime format?

从Pandas的文档中我读到,当执行 pandas.df.plot() 时,这也与 gcf().autofmt_xdate() 一起执行。我想放置我的自定义日期时间格式,但是当我尝试时,我的自定义日期格式与Pandas图默认给出的日期重叠。?有没有办法跳过 gcf().autofmt_xdate() 创建绘图??我如何为Pandas提供自定义日期时间格式?

Here is the generated plot.

这是生成的图。

enter image description here

在此处输入图片说明

Here is the python code.

这是python代码。

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
from pandas import Series
import pickle
datos = pickle.load(open("datos_reporte.pickle", "r"))
reload(plt)
series_o = []
series_p_h = []
series_p_d = []
series_names = []
for cod_estacion in datos.keys():
    x = [d[0] for d in datos[cod_estacion]['historial_semanal']]
    y = [d[1] for d in datos[cod_estacion]['historial_semanal']]
    s = Series(y, x)
    series_o.append(s.groupby(level=0).first())

df1 = pd.concat(series_o, join='outer', axis=1)
interval  = int(len(df1) / 12)
df1.columns = series_names
ax = plt.figure(figsize=(7,5), dpi=100).add_subplot(111)
df1.plot(ax=ax)
ax.xaxis.set_major_locator(mdates.HourLocator(interval=200))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d-%H:%S'))
ax.xaxis.grid(True, which="minor")
plt.title("Datos observados")
plt.ylabel('Caudal m^3/s')
plt.xlabel('Fecha')
plt.legend(loc=0,prop={'size': 7})
plt.xticks(rotation='vertical', fontsize = 8)
plt.subplots_adjust(bottom=.2)
plt.show()

回答by CT Zhu

I think you can just clear all the ticks before you make new ones:

我认为您可以在制作新刻度之前清除所有刻度:

df=pd.DataFrame({'A':np.random.random(20), 'B':np.random.random(20)})
df.index=pd.date_range('1/1/2014', periods=20, freq='5H')
ax = plt.figure(figsize=(7,5), dpi=100).add_subplot(111)
df.plot(ax=ax)
ax.set_xticks([])
ax.set_xticks([], minor=True)
ax.xaxis.set_major_locator(mdates.HourLocator(interval=200))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d-%H:%S'))
ax.xaxis.grid(True, which="minor")
plt.xticks(rotation='vertical', fontsize = 8)
plt.subplots_adjust(bottom=.2)

enter image description here

在此处输入图片说明

Edit

编辑

Now the labels are off. ax.xaxis.set_major_formatter(mdates.DateFormatter('%y/%m/%d-%H:%S'))will show they are 1991/01/11 and so on.

现在标签已关闭。ax.xaxis.set_major_formatter(mdates.DateFormatter('%y/%m/%d-%H:%S'))将显示它们是 1991/01/11 等等。

df=pd.DataFrame({'A':np.random.random(20), 'B':np.random.random(20)})
df.index=pd.date_range('1/1/2014', periods=20, freq='5H')
ax = plt.figure(figsize=(7,5), dpi=100).add_subplot(111)
ax.plot(df.index.to_pydatetime(), df.A, label='A')
ax.plot(df.index.to_pydatetime(), df.B, label='B')
ax.legend()
ax.xaxis.set_major_locator(mdates.HourLocator(interval=5))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%y/%m/%d-%H:%S'))
ax.xaxis.grid(True, which="major")
ax.yaxis.grid(True, which="major")
plt.xticks(rotation='vertical', fontsize = 8)
plt.subplots_adjust(bottom=.2)

enter image description here

在此处输入图片说明