使用 Pandas 在同一图中绘制不同 DataFrame 的不同列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45574099/
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
Plot different columns of different DataFrame in the same plot with Pandas
提问by Laura
I have two differents Data Frames:
我有两个不同的数据帧:
DF1: with columns A B1 C1 D1 E1
DF2: with columns A B2 C2 D2 E2
With A being the same for the two of them.
A 对他们两个来说是一样的。
then I want to plot two plots in the same figure, one at the right and the other at the left with this information:
然后我想在同一个图中绘制两个图,一个在右边,另一个在左边,带有以下信息:
Plot 1: x axis = column A
y axis = B1, B2, C1, C2 curves
Plot 2: x axis = column A
y axis = D1, D2, E1, E2 curves
How can I do it without merge the two DF using Pandas and Matplotlib?
如何在不使用 Pandas 和 Matplotlib 合并两个 DF 的情况下做到这一点?
回答by ImportanceOfBeingErnest
The idea would be to create an axes ax
and a twin axes ax2 = ax.twinx()
and to then plot each dataframe to one of them, df.plot(ax=ax)
and df2.plot(ax=ax2)
.
这个想法是创建一个轴ax
和一个双轴ax2 = ax.twinx()
,然后将每个数据框绘制到其中一个,df.plot(ax=ax)
并且df2.plot(ax=ax2)
.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
a = np.linspace(-5,5, 11)
data1 = np.sort(np.random.rand(len(a),5))
data1[:,0] =a
data2 = np.sort(np.random.rand(len(a),5))*10
data2[:,0] =a
df = pd.DataFrame(data1, columns=["A", "B1", "C1", "D1", "E1"])
df2 = pd.DataFrame(data2, columns=["A", "B2", "C2", "D2", "E2"])
fig, ax = plt.subplots()
ax2 = ax.twinx()
df.plot(x="A", y=["B1", "C1", "D1", "E1"], ax=ax)
df2.plot(x="A", y=["B2", "C2", "D2", "E2"], ax=ax2, ls="--")
plt.show()
If instead you want to have two separate plots (the question is not clear on this point), you can do it by
如果你想要有两个单独的图(这个问题在这一点上不清楚),你可以通过
fig, (ax, ax2) = plt.subplots(ncols=2)
and removing the twinx
call.
并取消twinx
通话。
回答by ml4294
You can use
您可以使用
f, (ax1, ax2) = plt.subplots(1,2)
which will create a plot containing 1 row and 2 columns of subplots. It will probably be the easiest way to obtain the columns of the data frames using
这将创建一个包含 1 行和 2 列子图的图。这可能是使用获取数据框列的最简单方法
A = DF1['A']
...
in case matplotlib does not like to be fed directly with the data frame columns.
如果 matplotlib 不喜欢直接输入数据框列。
You can then plot the columns into the different subplots. This looks like the following example:
然后,您可以将列绘制到不同的子图中。这类似于以下示例:
f, (ax1, ax2) = plt.subplots(1,2)
ax1.plot(A, B1, label='...')
ax1.plot(A, B2, label='...')
...
ax2.plot(A, D1, label='...')
ax2.plot(A, D2, label='...')
...
ax1.legend(loc='best')
ax2.legend(loc='best')
plt.show()