Koc*_*r4d 8 python matplotlib pandas
我有大熊猫DataFrame,df与index命名date和列columnA,columnB并columnC
我正在尝试使用语法将图散布index在x轴和columnAy轴上DataFrame。
当我尝试:
df.plot(kind='scatter', x='date', y='columnA')
我KeyError: 'date'可能会收到一个错误,可能是因为date不是列
df.plot(kind='scatter', y='columnA')
我可能会收到一个错误,ValueError: scatter requires and x and y column因此X轴上没有默认索引。
df.plot(kind='scatter', x=df.index, y='columnA')
我出错了KeyError: "DatetimeIndex(['1818-01-01', '1818-01-02', '1818-01-03', '1818-01-04',\n '1818-01-05', '1818-01-06', '1818-01-07', '1818-01-08',\n '1818-01-09', '1818-01-10',\n ...\n '2018-03-22', '2018-03-23', '2018-03-24', '2018-03-25',\n '2018-03-26', '2018-03-27', '2018-03-28', '2018-03-29',\n '2018-03-30', '2018-03-31'],\n dtype='datetime64[ns]', name='date', length=73139, freq=None) not in index"。
如果matplotlib.pyplot直接使用我可以画出来
plt.scatter(df.index, df['columnA'])
有没有一种方法可以x-axis使用DataFrame kind语法来绘制索引?
小智 10
至少pandas>1.4最简单的是:
df['columnA'].plot(style=".")
Run Code Online (Sandbox Code Playgroud)
这使您可以混合散点图和线图,以及使用标准 pandas 绘图界面
小智 8
一个更简单的解决方案是:
df['x1'] = df.index
Run Code Online (Sandbox Code Playgroud)
df.plot(kind='scatter', x='x1', y='columnA')
Run Code Online (Sandbox Code Playgroud)
只需在 plot 语句之外创建索引变量。
这有点丑陋(我认为您在问题中使用的matplotlib解决方案更好,FWIW),但是您始终可以使用索引作为列usinng创建一个临时DataFrame
df.reset_index()
Run Code Online (Sandbox Code Playgroud)
如果索引是无名的,则默认名称为'index'。假设是这种情况,您可以使用
df.reset_index().plot(kind='scatter', x='index', y='columnA')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7518 次 |
| 最近记录: |