1

I want a plot with two y-axes from two different data frame in one plot.

So far I tried to change the one data frame two y-axes version but I failed.

import pandas as pd
import matplotlib.pyplot as plt
plt.close("all")
df1 = pd.DataFrame({"x1": [1,2 ,3 ,4 ],
                   "y1_1": [555,525,532,585], 
                   "y1_2": [50,48,49,51]})
df2 = pd.DataFrame({"x2": [1, 2, 3,4],
                   "y2_1": [557,522,575,590], 
                   "y2_2": [47,49,50,53]})
ax1 = df1.plot(x="x1", y="y1_1", legend=False)
ax2 = ax1.twinx()
df1.plot(x="x1", y="y1_2", ax=ax2, legend=False, color="r")
ax3 = df2.plot(x="x2", y="y2_1", legend=False)
ax4 = ax1.twinx()
df2.plot(x="x2", y="y2_2", ax=ax4, legend=False, color="r")
plt.grid(True) 
ax1.figure.legend()
plt.show()

below this is what I want. enter image description here So far I have two plots but I want just everything in one plot.

1 Answer 1

2

Is this what you want:

ax1 = df1.plot(x="x1", y="y1_1", legend=False)
ax2=ax1.twinx()
df1.plot(x="x1", y="y1_2", ax=ax2, legend=False, color="r")
df2.plot(x="x2", y="y2_1", ax=ax1, legend=False)
df2.plot(x="x2", y="y2_2", ax=ax2, legend=False, color="r")

which gives:

enter image description here

Or, you can predefine ax1 and ax2, then pass them to plot functions:

fig, ax1 = plt.subplots()
ax2=ax1.twinx()

df1.plot(x="x1", y= ["y1_1"], ax=ax1, legend=False)
df1.plot(x="x1", y="y1_2", ax=ax2, legend=False, color="r")
df2.plot(x="x2", y="y2_1", ax=ax1, legend=False)
df2.plot(x="x2", y="y2_2", ax=ax2, legend=False, color="r")
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you very much, nice solution. Just one question why does have the grid only horizontally lines?
That just the default settings of my pyplot.
Ok, but I get the same result should not I get a different result or is my default the same as yours?
That's because you have plt.grid(True), remove it or change it it plt.grid(False).
Thanks, but it seems it can not work with element from a list because I got AttributeError: 'list' object has no attribute 'twinx'
|

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.