我有一些Pandas dataframe共享相同的值尺度,但有不同的列和索引。当调用df.plot()时,我得到单独的plot图像。我真正想要的是把它们都放在同一个情节中,作为次要情节,但不幸的是,我没能想出一个解决方案,非常感谢一些帮助。


当前回答

下面是一个工作中的pandas子图示例,其中modes是数据框架的列名。

    dpi=200
    figure_size=(20, 10)
    fig, ax = plt.subplots(len(modes), 1, sharex="all", sharey="all", dpi=dpi)
    for i in range(len(modes)):
        ax[i] = pivot_df.loc[:, modes[i]].plot.bar(figsize=(figure_size[0], figure_size[1]*len(modes)),
                                                   ax=ax[i], title=modes[i], color=my_colors[i])
        ax[i].legend()
    fig.suptitle(name)

其他回答

下面是一个工作中的pandas子图示例,其中modes是数据框架的列名。

    dpi=200
    figure_size=(20, 10)
    fig, ax = plt.subplots(len(modes), 1, sharex="all", sharey="all", dpi=dpi)
    for i in range(len(modes)):
        ax[i] = pivot_df.loc[:, modes[i]].plot.bar(figsize=(figure_size[0], figure_size[1]*len(modes)),
                                                   ax=ax[i], title=modes[i], color=my_colors[i])
        ax[i].legend()
    fig.suptitle(name)

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

fig, ax = plt.subplots(2,2)
df = pd.DataFrame({'A':np.random.randint(1,100,10), 
                   'B': np.random.randint(100,1000,10),
                   'C':np.random.randint(100,200,10)})
for ax in ax.flatten():
    df.plot(ax =ax)  


您可能根本不需要使用Pandas。这是cat频率的matplotlib图:

x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

f, axes = plt.subplots(2, 1)
for c, i in enumerate(axes):
  axes[c].plot(x, y)
  axes[c].set_title('cats')
plt.tight_layout()

您可以使用matplotlib手动创建子图,然后使用ax关键字在特定的子图上绘制数据帧。例如,对于4个子图(2x2):

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2)

df1.plot(ax=axes[0,0])
df2.plot(ax=axes[0,1])
...

这里的axes是一个包含不同子图轴的数组,您可以通过索引轴来访问其中一个。 如果你想要一个共享的x轴,那么你可以给plt.subplots提供sharex=True。

你可以用这个:

fig = plt.figure()
ax = fig.add_subplot(221)
plt.plot(x,y)

ax = fig.add_subplot(222)
plt.plot(x,z)
...

plt.show()