MATPLOTLIB - 在 x 轴上粘在一起的数据点

卢卡

我正在尝试在折线图上绘制数据。

我设法根据作业正确地做到了这一点,但我有一个小问题。我有一条连续的黑线,而不是在 x 轴上显示日期。实际上,数据框中的所有日期似乎都应用在图表上,因此粘在一起并使其成为一条长线。

这是我的代码

x = df['date']
y = df['value']

plt.figure(figsize=(18,8))
plt.title('Daily freeCodeCamp Forum Page Views 5/2016-12/2019')
plt.xlabel('Date')
plt.ylabel('Pageviews')

plt.plot(x, y, color = 'red', linewidth=1)

plt.show()

有人可以给我一个提示吗?

截屏

和风

我假设你的数据框是这样的:

           date     value
0    2020-01-01  2.160526
1    2020-01-02 -1.887699
2    2020-01-03  0.805389
3    2020-01-04 -0.680120
4    2020-01-05  0.658396

如果你打电话:

print(df.info())

你应该得到:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 366 entries, 0 to 365
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   date    366 non-null    object 
 1   value   366 non-null    float64
dtypes: float64(1), object(1)
memory usage: 4.4+ KB
None

注意列的 Dtype date:它是object. 这意味着 Pandas 将date存储str; 因此,首先,您需要转换strdatetime

df['date'] = pd.to_datetime(df['date'], format = '%Y/%m/%d')

在哪里'%Y/%m/%d'取决于数据存储在数据框中的格式。
现在你应该有:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 366 entries, 0 to 365
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   date    366 non-null    datetime64[ns]
 1   value   366 non-null    float64       
dtypes: datetime64[ns](1), float64(1)
memory usage: 5.8 KB
None

此时,您可以继续进行绘图:

fig, ax = plt.subplots()

ax.plot(df['date'], df['value'])

plt.show()

在此处输入图片说明

您可以根据需要自定义日期刻度:

ax.xaxis.set_major_locator(md.DayLocator(interval = 10))
ax.xaxis.set_major_formatter(md.DateFormatter('%B %d'))
plt.setp(ax.xaxis.get_majorticklabels(), rotation = 90)
ax.set_xlim([df['date'].iloc[0], df['date'].iloc[-1]])

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章