Python 如何将熊猫数据帧绘制为散点图?我想我可能把索引搞砸了,可以';不添加新索引吗?

Python 如何将熊猫数据帧绘制为散点图?我想我可能把索引搞砸了,可以';不添加新索引吗?,python,pandas,matplotlib,Python,Pandas,Matplotlib,我试图将我的步骤绘制成散点图,然后最终添加一条趋势线。 我设法让它与df.plot()一起工作,但它是一个折线图 以下是我尝试过的代码: import pandas as pd import matplotlib.pyplot as plt import numpy as np data_file = pd.read_csv('CSV/stepsgyro.csv') # print(data_file.head()) # put in the correct data types data

我试图将我的步骤绘制成散点图,然后最终添加一条趋势线。 我设法让它与df.plot()一起工作,但它是一个折线图

以下是我尝试过的代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

data_file = pd.read_csv('CSV/stepsgyro.csv')

# print(data_file.head())

# put in the correct data types
data_file = data_file.astype({"steps": int})
pd.to_datetime(data_file['date'])

# makes the date definitely the index at the bottom
data_file.set_index(['date'], inplace=True)

# sorts the data frame by the index
data_file.sort_values(by=['date'], inplace=True, ascending=True)
# data_file.columns.values[1] = 'date'

# plot the raw steps data
# data_file.plot()
plt.scatter(data_file.date, data_file.steps)
plt.title('Daily Steps')
plt.grid(alpha=0.3)
plt.show()

plt.close('all')

# plot the cumulative steps data
data_file = data_file.cumsum()
data_file.plot()
plt.title('Cumulative Daily Steps')
plt.grid(alpha=0.3)
plt.show()

plt.close('all')
下面是我的IDE上的屏幕截图:


任何指导都将不胜感激

我无法通过查看您的示例来理解为什么会出现这种错误。但是,我可以提供一个快速简便的解决方案来绘制数据:

data_file.plot(marker='.', linestyle='none')

我无法通过查看您的示例来理解为什么会出现这种错误。但是,我可以提供一个快速简便的解决方案来绘制数据:

data_file.plot(marker='.', linestyle='none')

您可以使用
df.plot(kind='scatter')
避开折线图。

您可以使用
df.plot(kind='scatter')
避开折线图。

您已经将索引设置为“日期”列。从那时起,不再有“日期”列,因此
data\u file.date
失败

两种选择:

  • 不要设置索引。无论如何,似乎不需要排序
  • 绘制索引,
    plt.scatter(data\u file.index,data\u file.steps)

  • 您已将索引设置为“日期”列。从那时起,不再有“日期”列,因此
    data\u file.date
    失败

    两种选择:

  • 不要设置索引。无论如何,似乎不需要排序
  • 绘制索引,
    plt.scatter(data\u file.index,data\u file.steps)

  • 您已将索引设置为“日期”列。从那一刻起,不再有“日期”列,因此
    data\u file.date
    失败。@importantanceofbeingernest嗯,我这样做是因为我想从索引中排序数据帧,有没有办法将索引用作散点x值?您已将索引设置为“日期”列。从那一刻起,不再有“日期”列,因此
    data\u file.date
    失败。@importantanceofbeingernest嗯,我这样做是因为我想从索引中排序数据帧,有没有办法将索引用作散点x值?谢谢:)这很有效,虽然我不确定是否可以添加一条趋势线:p我们将看到感谢:)这是有效的,但我不确定是否可以添加一条趋势线:p我们将看到