Define data
x = np.linspace(0,2*np.pi,100)
y = 2*np.sin(x)
Plot
fig = plt.figure()
ax = plt.axes()
fig.add_subplot(ax)
ax.plot(x,y)
Add second axis
newax = plt.axes(axisbg='none')
Gives me ValueError: Unknown element o, even though it does the same thing as what I am about to describe. I can also see that this works (no error) to do the same thing:
newax = plt.axes()
fig.add_subplot(newax)
newax.set_axis_bgcolor('none')
However, it turns the background color of the original figure “gray” (or whatever the figure background is)? I don’t understand, as I thought this would make newax transparent except for the axes and box around the figure. Even if I switch the order, same thing:
plt.close('all')
fig = plt.figure()
newax = plt.axes()
fig.add_subplot(newax)
newax.set_axis_bgcolor('none')
ax = plt.axes()
fig.add_subplot(ax)
ax.plot(x,y)
This is surprising because I thought the background of one would be overlaid on the other, but in either case it is the newax background that appears to be visible (or at least this is the color I see).
What is going on here?
You’re not actually adding a new axes.
Matplotlib is detecting that there’s already a plot in that position and returning it instead of a new axes object.
(Check it for yourself.
axandnewaxwill be the same object.)There’s probably not a reason why you’d want to, but here’s how you’d do it.
(Also, don’t call
newax = plt.axes()and then callfig.add_subplot(newax)You’re doing the same thing twice.)Edit: With newer (>=1.2, I think?) versions of matplotlib, you can accomplish the same thing as the example below by using the
labelkwarg to fig.add_subplot. E.g.newax = fig.add_subplot(111, label='some unique string')Of course, this looks awful, but it’s what you’re asking for…
I’m guessing from your earlier questions that you just want to add a second x-axis? If so, this is a completely different thing.
If you want the y-axes linked, then do something like this (somewhat verbose…):
If you want to have a hidden, unlinked y-axis, and an entirely new x-axis, then you’d do something like this:
Note that the y-axis values for anything plotted on
newaxare never shown.If you wanted, you could even take this one step further, and have independent x and y axes (I’m not quite sure what the point of it would be, but it looks neat…):
You can also just add an extra spine at the bottom of the plot. Sometimes this is easier, especially if you don’t want ticks or numerical things along it. Not to plug one of my own answers too much, but there’s an example of that here: How do I plot multiple X or Y axes in matplotlib?
As one last thing, be sure to look at the parasite axes examples if you want to have the different x and y axes linked through a specific transformation.