简体   繁体   English

使用熊猫创建子图

[英]Create subplots using pandas

I am trying to make 4 subplots using pandas.我正在尝试使用熊猫制作 4 个子图。 Here is my code:这是我的代码:

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] 

The columns 'MP_per_30min' and 'MP_per_1hour' are not completely filled with NaN values. 'MP_per_30min' 和 'MP_per_1hour' 列没有完全填充 NaN 值。 When I run the code, I get the plot but it is empty.当我运行代码时,我得到了情节,但它是空的。 Why is it not showing any values?为什么它不显示任何值?

As you are trying to plot each column as a different subplot.当您尝试将每一列绘制为不同的子图时。 It may be simpler to just let pandas do all the heavy lifting and get it to sort out the layout:让熊猫完成所有繁重的工作并让它整理布局可能更简单:


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()

Try the following code:试试下面的代码:

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()

The first correction is to filter out NaN values.第一个修正是过滤掉NaN值。

The second is to pass marker='o' , to draw at least markers for data points (by default the are not printed).第二个是传递marker='o' ,至少为数据点绘制标记(默认情况下不打印)。

Experiment also with only one of the above corrections.也仅使用上述修正之一进行试验。

And since you draw only 2 subplots, don't create 4 of them.由于您只绘制了 2 个子图,因此不要创建其中的 4 个。

Another option is to draw both subplots in one go:另一种选择是一次性绘制两个子图:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM