【问题标题】:Correctly depicting trends in matplotlib python like spreadsheet charts正确描绘 matplotlib python 中的趋势,如电子表格图表
【发布时间】:2018-11-26 00:03:42
【问题描述】:

我有一个包含日期和汽油价格的非常简单的数据集。

在 WPS 电子表格中如下图所示

但相同的数据集在 matplotlib python 中绘制如下

我正在绘制的数据框是

日期价格 0 2018-05-12 75.09 1 2018-05-13 75.09 2 2018-05-14 75.28 3 2018-05-15 75.42 4 2018-05-16 75.57 5 2018-05-17 75.78 6 2018-05-18 76.06 7 2018-05-19 76.34 8 2018-05-20 76.66 9 2018-05-21 76.98 10 2018-05-22 77.27 11 2018-05-23 77.55 12 2018-05-24 77.84 13 2018-05-25 78.19 14 2018-05-26 78.32 15 2018-05-27 78.46 16 2018-05-28 78.61 17 2018-05-29 78.76 18 2018-05-30 78.19 19 2018-05-31 78.68 20 2018-06-01 78.60 21 2018-06-02 78.51 22 2018-06-03 78.43 23 2018-06-04 78.43 24 2018-06-05 78.16 25 2018-06-06 78.05 26 2018-06-07 77.97 27 2018-06-08 77.77 28 2018-06-09 77.38 29 2018-06-10 77.15 30 2018-06-11 76.96 31 2018-06-12 76.82 32 2018-06-13 76.82

这是我用来绘制的代码 将 matplotlib.pyplot 导入为 plt 将数据集导入为 DS

df = DS.getDataSet_petrol("13-06-2018")

plt.plot(df['date'],df['price'])

plt.show()

显然看电子表格图表显示非线性趋势,而 matplotlib 显示线性趋势。

这让我对使用线性或多项式回归的正确回归模型感到困惑。

所以我的主要问题是: 如何让 python 绘图看起来像电子表格?

【问题讨论】:

  • 使用的是哪个版本的 matplolib?你能指出这些列的数据类型吗?
  • ... print(mpl.__version__) 后端​​ TkAgg 是交互式后端。打开交互模式。 2.2.2
  • 对于这两列
  • 只发df.dtypes的回复
  • date datetime64[ns] price object dtype: object

标签: python date matplotlib


【解决方案1】:

问题似乎是由您的df["price"] 中的字符串对象引起的。

这可以通过在绘制之前将其转换为浮点数来解决。

plt.plot(df['date'],df['price'].astype('float'))

甚至在对数据进行任何操作之前:

df['price'] = df['price'].astype('float')

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 2020-11-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2019-06-15
    • 2022-07-25
    • 2014-07-30
    相关资源
    最近更新 更多