Python 如何将单独的 Pandas DataFrames 绘制为子图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22483588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:01:25  来源:igfitidea点击:

How can I plot separate Pandas DataFrames as subplots?

pythonmatplotlibpandas

提问by Jimmy C

I have a few Pandas DataFrames sharing the same value scale, but having different columns and indices. When invoking df.plot(), I get separate plot images. what I really want is to have them all in the same plot as subplots, but I'm unfortunately failing to come up with a solution to how and would highly appreciate some help.

我有几个 Pandas DataFrames 共享相同的值比例,但具有不同的列和索引。调用时df.plot(),我会得到单独的绘图图像。我真正想要的是将它们全部与子图放在同一个情节中,但不幸的是,我未能提出解决方案,并且非常感谢您的帮助。

采纳答案by joris

You can manually create the subplots with matplotlib, and then plot the dataframes on a specific subplot using the axkeyword. For example for 4 subplots (2x2):

您可以使用 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])
...

Here axesis an array which holds the different subplot axes, and you can access one just by indexing axes.
If you want a shared x-axis, then you can provide sharex=Trueto plt.subplots.

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

回答by sedeh

You can see e.gs. in the documentationdemonstrating joris answer. Also from the documentation, you could also set subplots=Trueand layout=(,)within the pandas plotfunction:

你可以看到例如 在演示 joris 答案的文档中。同样从文档中,您还可以在 pandas函数中设置subplots=True和: layout=(,)plot

df.plot(subplots=True, layout=(1,2))

You could also use fig.add_subplot()which takes subplot grid parameters such as 221, 222, 223, 224, etc. as described in the post here. Nice examples of plot on pandas data frame, including subplots, can be seen in this ipython notebook.

你也可以使用fig.add_subplot()这需要插曲电网参数,如221,222,223,224,等,在后描述这里。在这个 ipython notebook 中可以看到熊猫数据框上的很好的绘图示例,包括子图。

回答by Q-man

You can use the familiar Matplotlib style calling a figureand subplot, but you simply need to specify the current axis using plt.gca(). An example:

您可以使用熟悉的 Matplotlib 样式调用 afiguresubplot,但您只需要使用 指定当前轴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())

etc...

等等...

回答by DaveL17

Building on @joris response above, if you have already established a reference to the subplot, you can use the reference as well. For example,

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

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

df.plot.barh(ax=ax1, stacked=True)

回答by Joe

You can use this:

你可以使用这个:

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

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

plt.show()

回答by duhaime

You may not need to use Pandas at all. Here's a matplotlib plot of cat frequencies:

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

enter image description here

在此处输入图片说明

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

回答by Dr. Arslan

You can plot multiple subplots of multiple pandas data frames using matplotlib with a simple trick of making a list of all data frame. Then using the for loop for plotting subplots.

您可以使用 matplotlib 绘制多个 Pandas 数据框的多个子图,并使用一个简单的技巧来制作所有数据框的列表。然后使用 for 循环绘制子图。

Working code:

工作代码:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# dataframe sample data
df1 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df2 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df3 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df4 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df5 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df6 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
#define number of rows and columns for subplots
nrow=3
ncol=2
# make a list of all dataframes 
df_list = [df1 ,df2, df3, df4, df5, df6]
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
    for c in range(ncol):
        df_list[count].plot(ax=axes[r,c])
        count=+1

enter image description here

在此处输入图片说明

Using this code you can plot subplots in any configuration. You need to just define number of rows nrowand number of columns ncol. Also, you need to make list of data frames df_listwhich you wanted to plot.

使用此代码,您可以在任何配置中绘制子图。您只需要定义行nrow数和列数ncol。此外,您需要列出df_list要绘制的数据框。