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


当前回答

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)  


其他回答

您可以使用熟悉的Matplotlib样式调用图形和子图,但是您只需要使用plt.gca()指定当前轴。一个例子:

plt.figure(1)
plt.subplot(2,2,1)
df.A.plot() #no need to specify for first axis
plt.subplot(2,2,2)
df.B.plot(ax=plt.gca())
plt.subplot(2,2,3)
df.C.plot(ax=plt.gca())

等等……

在上面的@joris响应的基础上,如果已经建立了对子图的引用,那么也可以使用该引用。例如,

ax1 = plt.subplot2grid((50,100), (0, 0), colspan=20, rowspan=10)
...

df.plot.barh(ax=ax1, stacked=True)
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)  


你可以用这个:

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

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

plt.show()

下面是一个工作中的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)