繁体   English   中英

对于折线图(matplotlib,pandas)的 dataframe 中缺少 x 值,如何将 y 值设置为 0

[英]How do I set y value as 0 for missing x values in dataframe for line graph (matplotlib, pandas)

我有一个 dataframe 用于 plot 折线图。 Dataframe 看起来像这样:

这是我的折线图目前的样子:
线形图

代码为 plot 折线图:

ax  = df_dec18.set_index('Day').plot(figsize=(10,5), grid=True)
ax.set_xlabel('Day')
ax.set_ylabel('Number of reviews')
ax.set_title('Number of reviews published each month in year 2018 (September onwards) for HP 15q ds0058TU')
t = [df_dec18['Reviews_published'].min(), df_dec18['Reviews_published'].max()]
plt.xticks(range(0,31))

我如何将第 7、8、9 天的 x 值设置为 0,因为那天没有发表评论。 我想这样做,所以我的折线图 y 值在给定日期显示为 0。

据我所知,您不能直接告诉 matplotlib 在缺失数据中输入零。 Matplotlib 只是忽略丢失的数据,并在您有数据的点之间连接线。 如果您希望丢失的数据为零,则应将其作为 dataframe 处理的一部分。

这样的处理可以是:

df_dec18 = df_dec18.set_index('Day')
df_new_dec18 = pd.DataFrame({"Day":range(1,32), "Reviews_published": 0}).set_index("Day")
df_new_dec18["Reviews_published"]=df_dec18["Reviews_published"]
df_new_dec18.fillna(0, inplace=True)

起初,我将“Day”列作为 dataframe 的索引。 您正在使用时间序列(我猜),我认为使用您的一天作为索引更方便。 然后我创建了一个新的 df,这次是在 12 月的一整天,而不仅仅是你有数据的那些。 同样,当您使用时间序列时,我相信这是处理 dataframe 的更正确和“干净”的方式。 此 dataframe 也使用“日”作为索引。

然后我只是使用fillna将您没有任何信息的天数归零。 然后你的折线图会很好。 请注意,您将需要不带set_indexax = df_dec18.plot(figsize=(10,5), grid=True) ,因为“Day”列已经是索引。

PS:下一次,请将您的 dataframe 内联示例(就像您的代码一样)而不是图像。 对于您的线图,只需复制它 - 右键单击 juypter 并“复制图像”并将其粘贴到此处。 不要共享整个屏幕。

暂无
暂无

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

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