Reputation: 56242
I want to draw a plot with matplotlib with axis on both sides of the plot, similar to this plot (the color is irrelevant to this question):
How can I do this with matplotlib
?
Note: contrary to what is shown in the example graph, I want the two axis to be exactly the same, and want to show only one graph. Adding the two axis is only to make reading the graph easier.
Upvotes: 28
Views: 67040
Reputation: 51
The documentation is very helpful. For showing the same y axis ticks and tick labels on both the left side and the right side of a plot, I have had good, consistent results with the following:
ax0 = ax.twinx()
ax0.set_ylim(ax.get_ylim())
ax0.set_yticks(ax.get_yticks(), ax.get_yticklabels(),
fontsize= 8)
where ax is the default display with y's ticks and tick labels on the left. This first line of code creates ax0 to share the x axis with ax (twinx()). The second line sets the min and max values for ax0's y axis to match those of ax's y axis. The last line sets ax0's y ticks and tick labels to match those of ax.
For two, separate y axes, see John Bartholomew's remarks and references above.
Upvotes: 1
Reputation: 558
I've done this previously using the following:
# Create figure and initial axis
fig, ax0 = plt.subplots()
# Create a duplicate of the original xaxis, giving you an additional axis object
ax1 = ax.twinx()
# Set the limits of the new axis from the original axis limits
ax1.set_ylim(ax0.get_ylim())
This will exactly duplicate the original y-axis.
Eg:
ax = plt.gca()
plt.bar(range(3), range(1, 4))
plt.axhline(1.75, color="gray", ls=":")
twin_ax = ax.twinx()
twin_ax.set_yticks([1.75])
twin_ax.set_ylim(ax.get_ylim())
Upvotes: 2
Reputation: 5325
You can use tick_params() (this I did in Jupyter notebook):
import matplotlib.pyplot as plt
bar(range(10), range(10))
tick_params(labeltop=True, labelright=True)
Generates this image:
UPD: added a simple example for subplots. You should use tick_params()
with axis object.
This code sets to display only top labels for the top subplot and bottom labels for the bottom subplot (with corresponding ticks):
import matplotlib.pyplot as plt
f, axarr = plt.subplots(2)
axarr[0].bar(range(10), range(10))
axarr[0].tick_params(labelbottom=False, labeltop=True, labelleft=False, labelright=False,
bottom=False, top=True, left=False, right=False)
axarr[1].bar(range(10), range(10, 0, -1))
axarr[1].tick_params(labelbottom=True, labeltop=False, labelleft=False, labelright=False,
bottom=True, top=False, left=False, right=False)
Looks like this:
Upvotes: 78
Reputation: 6586
There are a couple of relevant examples in the online documentation:
Upvotes: 22