Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot secondary_y in log scale in pyplot

Tags:

matplotlib

I would like to have two lines (or better scatter plots) in one plot.

The Secondary Y line should be in log scale. How to do it with python matplotlib?

like image 323
Andrej Mikulik Avatar asked Mar 10 '23 13:03

Andrej Mikulik


1 Answers

You can create a second y axis by using ax2 = ax.twinx(). You can then, as tacaswell pointed out in the comments, set this second axis to log scale.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(5,3))
ax = fig.add_subplot(111)
ax2 = ax.twinx()

x = np.random.rand(10)
y = np.random.rand(10)
y2 = np.random.randint(1,10000, size=10)

l1 = ax.scatter(x,y, c="b", label="lin")
l2 = ax2.scatter(x,y2,  c="r", label="log")

ax2.set_yscale("log")
ax2.legend(handles=[l1, l2])

ax.set_ylabel("Linear axis")
ax2.set_ylabel("Logarithmic axis")
plt.tight_layout()

plt.show()

enter image description here

like image 92
ImportanceOfBeingErnest Avatar answered Mar 13 '23 04:03

ImportanceOfBeingErnest