首页 > 解决方案 > pyplot 输出看起来不正确

问题描述

第一个问题在这里问。我希望我做对了。如果我应该提供更多信息或者我的问题不清楚,请告诉我。

我正在尝试使用 python (pandas、seaborn、matplotlib) 来生成折线图。在玩了很多之后,脚本运行但输出看起来不正确。原始数据比我的脚本输出中显示的要平滑得多。我将它与在 excel 中生成的图表进行了比较,看起来更加逼真。我真的不明白我的脚本出了什么问题。

该数据集是“RBD Palm Olein FOB Malaysia”的每日收盘价。第 1 列是日期,第 2 列是价格。数据保存为 CSV。我能想到的唯一问题是市场休市时缺少的日子。这可能是问题吗?

代码如下:

import pandas as pd
df = pd.read_csv("/Users/michaelkingston/Desktop/RBDP2015_20.csv")
print(df)
df.info()
df['ds']= pd.to_datetime(df['ds'])
df.info()
import seaborn as sns
sns.lineplot(x="ds",
        y="Y",
        data=df)
import matplotlib.pyplot as plt
plt.show()

这是 excel 输出的 图像 在此处输入图像描述

这是python输出 在此处输入图像描述

print(df.head)

<bound method NDFrame.head of              ds    Y
0    2015-02-01  673
1    2015-05-01  663
2    2015-06-01  663
3    2015-07-01  668
4    2015-08-01  680
...         ...  ...
1419 2020-10-23  775
1420 2020-10-26  805
1421 2020-10-27  810
1422 2020-10-28  828
1423 2020-10-29  825

标签: pythonseaborn

解决方案


我觉得根据数据你的输出是正确的,它与你在 excel 中得到的不同,因为 python 的绘图被压缩到默认绘图大小,你可以调整绘图的大小以在 excel 中拉伸它。另一点是:如果您像在 excel 中一样需要 x 轴标签,那么最好不要将日期列转换为日期时间对象,因为在绘制日期时间对象时,matplotlib 仅显示几个日期以确保可读性。

以下是您可以尝试的方法:

import matplotlib.pyplot as plt    

#converting the column ds to string type    
df['ds'] = df['ds'].astype(str)    

#fixing a big figure size for the plot    
plt.figure(figsize=(25,10))

sns.lineplot(x="ds", y="Y", data=df)

#for making the x-axis labels rotate by 90 degree to avoid cluttering of tick labels    
plt.xticks(rotation=90)
plt.show()

推荐阅读