使用Pandas在同一图中绘制不同DataFrame的不同列 [英] Plot different columns of different DataFrame in the same plot with Pandas

查看:122
本文介绍了使用Pandas在同一图中绘制不同DataFrame的不同列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的数据框:

I have two differents Data Frames:

DF1: with columns A B1 C1 D1 E1
DF2: with columns A B2 C2 D2 E2

两个人的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

如何在不使用Pandas和Matplotlib合并两个DF的情况下做到这一点?

How can I do it without merge the two DF using Pandas and Matplotlib?

推荐答案

该想法是创建一个轴ax和一个双轴ax2 = ax.twinx(),然后将每个数据帧绘制到其中一个df.plot(ax=ax)df2.plot(ax=ax2).

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

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)

并删除twinx调用.

这篇关于使用Pandas在同一图中绘制不同DataFrame的不同列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆