Issue
I have a graph showing x4 vs y:
y is the log of some other variable, say q (i.e. y = log(q) ) the value of q is what the layperson will understand when reading this graph.
I want to set up a secondary axis on the right side of the graph, where the lines are at the same vertical position as the left-hand axis, but the label is replaced by the equivalent q value - i.e. exp(y) - to 2 decimal places.
Is there an efficient way to create a secondary axis which does this mapping from the primary y axis?
I'm using pyplot
from matplotlib
. Some example starting code:
import numpy as np
import matplotlib.pyplot as plt
q = np.random.rand(100,)
y = np.log(q)
x4 = np.random.rand(100,)
plt.scatter(x4, y)
I want to add a second axis, which has the same vertical positions and spacing as the primary axis, but the labels are replaced by exp(y). Also include an axis label "q".
Thank you
Solution
My suggestion here would be to use a twin axes and share it will the original axes to fix the tick positions. You may then use a FuncFormatter
to give the ticks the correct labels. The advantage of this is that you do not need to fix the limits of the plot a priori and can freely zoom and pan inside the plot.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
f = lambda q: np.log(q)
finv = lambda x: np.exp(x)
x = np.random.rand(100,)
y = f(np.random.rand(100,))
fig, ax = plt.subplots()
ax2 = ax.twinx()
ax.get_shared_y_axes().join(ax,ax2)
ax.scatter(x, y)
ax2.yaxis.set_major_formatter(FuncFormatter(lambda x,pos: f"{finv(x):.2f}"))
plt.show()
Answered By - ImportanceOfBeingErnest
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.