【问题标题】:Plot two pandas data frames side by side, each in subplot style并排绘制两个 pandas 数据框,每个数据框都采用子图样式
【发布时间】:2018-08-06 23:36:13
【问题描述】:

我想并排绘制两个熊猫数据框,每个图都应该是子图形式。我正在使用以下几行:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# create dummy pandas dataframes
pd1 = pd.DataFrame({'a':np.random.random(22),'b':np.random.random(22),'c':np.random.random(22)})
pd2 = pd.DataFrame({'J':np.random.random(22),'K':np.random.random(22),'P':np.random.random(22)})
#create subplot figure with having two side by side plots
fig, axes = plt.subplots(nrows=1,ncols=2,figsize=(12,6))
# plot first pandas frame in subplot style
pd1.plot(ax = axes[0],subplots=True) 
# plot second pandas frame in subplot style
pd2.plot(ax = axes[1],subplots=True)

如果没有 subplot 选项,将绘制并排的图,但我想要 subplot 样式。有没有其他方法可以完成它?

确切地说,我想以下列方式绘制熊猫:

【问题讨论】:

  • 什么是“子情节风格”?请描述您想要实现的目标。
  • 我用一个图更新了我的问题

标签: python pandas matplotlib


【解决方案1】:

您需要一个 3 行 2 列的子图网格来托管您的图。然后ax 参数需要采用您想要将 3 个数据框列绘制到的 3 个轴。

fig, axes = plt.subplots(nrows=3,ncols=2)
pd1.plot(ax = axes[:,0], subplots=True) 
pd2.plot(ax = axes[:,1], subplots=True)

完整代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# create dummy pandas dataframes
pd1 = pd.DataFrame({'a':np.random.random(22),'b':np.random.random(22),
                    'c':np.random.random(22)})
pd2 = pd.DataFrame({'J':np.random.random(22),'K':np.random.random(22),
                    'P':np.random.random(22)})
#create subplot figure with having two side by side plots
fig, axes = plt.subplots(nrows=3,ncols=2,figsize=(12,6))
# plot first pandas frame in subplot style
pd1.plot(ax = axes[:,0],subplots=True) 
# plot second pandas frame in subplot style
pd2.plot(ax = axes[:,1],subplots=True)

plt.show()

【讨论】:

  • 当两个数据框的列数不同时,我仍然会遇到问题。我认为这是一个不同的问题,我需要为此找到一些解决方法。
  • 您需要创建子图网格,以便它可以托管数据框图创建的子图的数量。然后确保提供给ax 的轴列表具有精确的轴数,因为有要绘制的列。根据要绘制的列数,您可能无法使用plt.subplots 创建网格,而是一个接一个地创建子图或使用gridspec
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多