Python 使用Matplotlib绘制日期-随机(显然)年

Python 使用Matplotlib绘制日期-随机(显然)年,python,pandas,matplotlib,Python,Pandas,Matplotlib,我试图绘制一个从Yahoo finance()下载的简单的.csv文件,但我无法理解为什么年份(显然)是随机数。请参阅下图: 我想做的另一件事是从顶部图形中删除x轴(因为相同的轴已经在底部绘图中),但我想保留虚线网格。我已经厌倦了使用ax[0]。设置\xticklabels([]),但它不起作用。 这是我的密码: import pandas as pd import matplotlib.pyplot as plt from matplotlib.dates import DateFormatt

我试图绘制一个从Yahoo finance()下载的简单的.csv文件,但我无法理解为什么年份(显然)是随机数。请参阅下图:

我想做的另一件事是从顶部图形中删除x轴(因为相同的轴已经在底部绘图中),但我想保留虚线网格。我已经厌倦了使用ax[0]。设置\xticklabels([]),但它不起作用。 这是我的密码:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, MonthLocator, YearLocator


#LOAD DATA
df_name = "0P0000UL8U.L.csv"
col_list = ["Date", "Adj Close"] #list of column to import
df = pd.read_csv(df_name, header=0, usecols=col_list, na_values=['null'], thousands=r',', parse_dates=["Date"], dayfirst=True)
df = df.dropna() #Drop the rows where at least one element is missing.
df.set_index("Date", inplace = True)
df.index = [pd.to_datetime(date).date() for date in df.index] #convert index to datetime.date, not datetime.datetime.
print("Opening df:\n", df)
print("\nLength of df: ", len(df.index))


#PLOT DATA
fig, ax = plt.subplots(2,1, figsize=(11,5))
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.25, hspace=0.8) #Adjust space between graphs

df[["Adj Close"]].plot(ax=ax[0], kind="line", style="-", color="blue", stacked=False, rot=90)
ax[0].set_axisbelow(True)  # To put plot grid below plots
ax[0].yaxis.grid(color='gray', linestyle='dashed')
ax[0].xaxis.grid(color='gray', linestyle='dashed')
ax[0].xaxis.set_major_locator(YearLocator())  # specify a MonthLocator
ax[0].xaxis.set_major_formatter(DateFormatter("%b %Y"))
ax[0].set(xlabel=None, ylabel="Price")  # Set title and labels for axes

df[["Adj Close"]].plot(ax=ax[1], kind="line", style="-", color="blue", stacked=False, rot=90)
ax[1].set_axisbelow(True)  # To put plot grid below plots
ax[1].yaxis.grid(color='gray', linestyle='dashed')
ax[1].xaxis.grid(color='gray', linestyle='dashed')
ax[1].xaxis.set_major_locator(YearLocator())  # specify a MonthLocator
ax[1].xaxis.set_major_formatter(DateFormatter("%b %Y"))
ax[1].set(xlabel="Time", ylabel="Price")  # Set title and labels for axes

fig.savefig("0P0000UL8U.L.png", bbox_inches='tight', dpi=300)

我做错了什么?提前感谢您的帮助。

要从顶部图表中删除x轴标签,您可以添加以下行:

ax[0]。勾选参数(labelbottom=False)


在ax[0]之前设置(xlabel=None,ylabel=“Price”)这不是你的错。Python3还远远不够稳定。这就是为什么硬核开发人员仍然喜欢Python2。这一次,自民党在处理问题上犯了错误。它们甚至有一些相应的bug(#18010、#17983、#34850)。
同时,您可以将matplotlib降级到V3.2.2,它工作正常,等待开发人员修复错误。

在随机年份,我无法重现该问题(它在我的电脑上正确显示)。也许可以检查你的系统时间是否同步。感谢你为顶部绘图的x轴提供的解决方案。关于日期,您所说的“系统时间同步”是什么意思?Python也给了我以下警告:MatplotlibDeprecationWarning:epoch2num函数在Matplotlib 3.3中被弃用,将在两个次要版本后删除。base=dates.epoch2num(dt.asi8/1.0e9)有什么想法吗?谢谢。我指的是要与实时同步的系统时间(操作系统日历/时钟)(尽管我怀疑在大多数情况下不是这样)。在我的例子中,它与Matplotlib 3.1.2一起工作,所以您可能会认为日历系统似乎是同步的。可能是因为日期序列不是连续的(即天数中存在间隔)?顺便说一句,这就是为什么正确使用代码很重要,而不是使用
df['Date']=df['Date'].dt.strftime(“%d/%m/%Y”)
。。。