使用熊猫创建子图

时间:2020-10-22 18:19:58

标签: python pandas

我正在尝试使用熊猫制作4个子图。这是我的代码:

fig_MP_sec, axes1 = plt.subplots(nrows=4, ncols=1)
df['MP_per_30min'].plot(ax=axes1[0])
axes1[0].set_title('MP averaged over a 1s time interval')
df['MP_per_1hour'].plot(ax=axes1[1])
plt.show()
df
Out[4]: 
                               MP   log2_MP  ...  MP_per_30min  MP_per_1hour
Date_and_time                                ...                            
2020-08-02 21:21:46.082191   97.0  6.599913  ...           NaN           NaN
2020-08-02 21:21:46.164383   21.0  4.392317  ...           NaN           NaN
2020-08-02 21:21:46.246575    0.0      -inf  ...           NaN           NaN
2020-08-02 21:21:46.328767    0.0      -inf  ...           NaN           NaN
2020-08-02 21:21:46.410958    0.0      -inf  ...           NaN           NaN
                          ...       ...  ...           ...           ...
2020-08-03 02:15:00.807537  801.0  9.645658  ...           NaN           NaN
2020-08-03 02:15:00.847913  834.0  9.703904  ...           NaN           NaN
2020-08-03 02:15:00.888290  821.0  9.681238  ...           NaN           NaN
2020-08-03 02:15:00.928667  709.0  9.469642  ...           NaN           NaN
2020-08-03 02:15:00.969044  716.0  9.483816  ...           NaN           NaN

[263647 rows x 13 columns] 

“ MP_per_30min”和“ MP_per_1hour”列未完全用NaN值填充。当我运行代码时,我得到了情节,但它是空的。为什么不显示任何值?

2 个答案:

答案 0 :(得分:0)

在尝试将每列绘制为不同的子图时。让熊猫来完成所有繁重的工作,然后整理一下布局,可能会更简单:


columns = ['MP_per_30min','MP_per_1hour']

df[columns].plot(subplots=True, layout=(4, 1), figsize=(6, 6), sharex=True)

import matplotlib.pyplot as plt
plt.show()

答案 1 :(得分:0)

尝试以下代码:

fig_MP_sec, axes1 = plt.subplots(nrows=2, ncols=1)
df['MP_per_30min'].dropna().plot(ax=axes1[0], marker='o')
df['MP_per_1hour'].dropna().plot(ax=axes1[1], marker='o')
plt.show()

第一个更正是过滤出 NaN 值。

第二种方法是传递 marker ='o',以至少绘制 数据点标记(默认情况下不会打印)。

也只能进行上述一项更正。

由于您仅绘制2个子图,因此请勿创建4个子图。

另一种选择是一次性绘制两个子图:

df[['MP_per_30min', 'MP_per_1hour']].interpolate().plot(subplots=True, legend=False);