7

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?

2 Answers 2

20

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

Sign up to request clarification or add additional context in comments.

1 Comment

Mindblown that no one else has upvoted this, yet. Great explanation and solid figures.
0

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

A = DF1['A']
...

in case matplotlib does not like to be fed directly with the data frame columns.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.