Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot different columns of different DataFrame in the same plot with Pandas

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.

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?

like image 688
Laura Avatar asked Aug 08 '17 17:08

Laura


People also ask

How do you plot two DataFrames in the same plot?

MatPlotLib with Python Set the figure size and adjust the padding between and around the subplots. Create two Pandas dataframes, df1 and df2, of two-dimensional, size-mutable, potentially heterogeneous tabular data. Plot df1 and df2 using plot() method. To display the figure, use show() method.

How do I plot different columns in pandas?

Pandas has a tight integration with Matplotlib. You can plot data directly from your DataFrame using the plot() method. To plot multiple data columns in single frame we simply have to pass the list of columns to the y argument of the plot function.


1 Answers

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

enter image description here

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.

enter image description here

like image 200
ImportanceOfBeingErnest Avatar answered Oct 18 '22 05:10

ImportanceOfBeingErnest