i would like to stack 2 subplots so that one of them is in front of the other one. In addition to that i would like to set the size of the subplot in the back a little bit bigger than the subplot in the front in order to see the edges. Here is an example how it should look.
For both subplots i need to use ax = Subplot(fig,111) and fig.add_subplot(ax) cause i want to implement a gridhelper in the subplots.
Is it possible to change the size of ax2 without changing ax1 so that ax2 in the background is slightly bigger than ax1 ?
This might get you on the right track, although I am not sure how it influences your grid helper requirement:
import numpy as np
from matplotlib import pyplot as plt
x, y = np.linspace(-5, 5, 1024), np.linspace(-5, 5, 1024)
fig = plt.figure()
ax = fig.add_axes((0,0,1,1)) # lower_x, lower_y, width, height
ax.plot(x,y)
ax = fig.add_axes((0.2,0.2,.6,.6))
ax.plot(x,y)
source: here
Related
With matplotlib, I want to plot two graphs with the same x-axis scale, but I want to show different sized sections. How can I accomplish that?
So far I can plot differently sized subplots with GridSpec or same sized ones who share the x-axis. When I try both at once, the smaller subplot has the same axis but smaller scaled, while I want the same scaling and a different axis, so sharing the axis might be a wrong idea.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
x=np.linspace(0,10,100)
y=np.sin(x)
x2=np.linspace(0,5,60)
y2=np.cos(x2)
fig=plt.figure()
gs=GridSpec(2,3)
ax1 = fig.add_subplot(gs[0, :])
ax1.plot(x,y)
ax2 = fig.add_subplot(gs[1,:-1])
#using sharex=ax1 here decreases the scaling of ax2 too much
ax2.plot(x2,y2)
plt.show()
I want the x.axes to have the same scaling, i.e. the same x values are always exactly on top of each other, this should give you an idea. The smaller plot's frame could be expanded or fit the plot, that doesn't matter. As it is now, the scales don't match.
Thanks in advance.
This is still a bit rough. I'm sure there's a slightly more elegant way to do this, but you can create a custom transformation (see Transformations Tutorial) between the Axes coordinates of ax2 and the data coordinates of ax1. In other word, your calculating what is the data-value (according to ax1) at the position corresponding to the left and right edges of ax2, and then adjust the xlim of ax2 accordingly.
Here is a demonstration showing that it works even if the second subplot is not aligned in any particular way with the first.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
x=np.linspace(0,25,100)
y=np.sin(x)
x2=np.linspace(10,30,60)
y2=np.cos(x2)
fig=plt.figure()
gs=GridSpec(2,6)
ax1 = fig.add_subplot(gs[0, :])
ax1.plot(x,y)
ax2 = fig.add_subplot(gs[1,3:-1])
ax2.plot(x2,y2)
# here is where the magic happens
trans = ax2.transAxes + ax1.transData.inverted()
((xmin,_),(xmax,_)) = trans.transform([[0,1],[1,1]])
ax2.set_xlim(xmin,xmax)
# for demonstration, show that the vertical lines end up aligned
for ax in [ax1,ax2]:
for pos in [15,20]:
ax.axvline(pos)
plt.show()
EDIT: One possible refinement would be to do the transform in the xlim_changed event callback. That way, the axes stay in sync even when zooming/panning in the first axes.
There is also a slight issue with tight_layout() as you noted, but that is easily fixed by calling the callback function directly.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
def on_xlim_changed(event):
# here is where the magic happens
trans = ax2.transAxes + ax1.transData.inverted()
((xmin, _), (xmax, _)) = trans.transform([[0, 1], [1, 1]])
ax2.set_xlim(xmin, xmax)
x = np.linspace(0, 25, 100)
y = np.sin(x)
x2 = np.linspace(10, 30, 60)
y2 = np.cos(x2)
fig = plt.figure()
gs = GridSpec(2, 6)
ax1 = fig.add_subplot(gs[0, :])
ax1.plot(x, y)
ax2 = fig.add_subplot(gs[1, 3:-1])
ax2.plot(x2, y2)
# for demonstration, show that the vertical lines end up aligned
for ax in [ax1, ax2]:
for pos in [15, 20]:
ax.axvline(pos)
# tight_layout() messes up the axes xlim
# but can be fixed by calling on_xlim_changed()
fig.tight_layout()
on_xlim_changed(None)
ax1.callbacks.connect('xlim_changed', on_xlim_changed)
plt.show()
I suggest setting limits of the second axis based on the limits of ax1.
Try this!
ax2 = fig.add_subplot(gs[1,:-1])
ax2.plot(x2,y2)
lb, ub = ax1.get_xlim()
# Default margin is 0.05, which would be used for auto-scaling, hence reduce that here
# Set lower bound and upper bound based on the grid size, which you choose for second plot
ax2.set_xlim(lb, ub *(2/3) -0.5)
plt.show()
I am trying to make 4 subplots (2x2) with an inverted y axis while also sharing the y axis between subplots. Here is what I get:
import matplotlib.pyplot as plt
import numpy as np
fig,AX = plt.subplots(2, 2, sharex=True, sharey=True)
for ax in AX.flatten():
ax.invert_yaxis()
ax.plot(range(10), np.random.random(10))
It appears that ax.invert_axis() is being ignored when sharey=True. If I set sharey=False I get an inverted y axis in all subplots but obviously the y axis is no longer shared among subplots. Am I doing something wrong here, is this a bug, or does it not make sense to do something like this?
Since you set sharey=True, all three axes now behave as if their were one. For instance, when you invert one of them, you affect all four. The problem resides in that you are inverting the axes in a for loop which runs over an iterable of length four, you are thus inverting ALL axes for an even number of times... By inverting an already inverted ax, you simply restore its original orientation. Try with an odd number of subplots instead, and you will see that the axes are successfully inverted.
To solve your problem, you should invert the y-axis of one single subplot (and only once). Following code works for me:
import matplotlib.pyplot as plt
import numpy as np
fig,AX = plt.subplots(2, 2, sharex=True, sharey=True)
## access upper left subplot and invert it
AX[0,0].invert_yaxis()
for ax in AX.flatten():
ax.plot(range(10), np.random.random(10))
plt.show()
It seems the only way I can make the figure a rectangle (to save vertical space), is by skewing the image which makes all text on the screen skew also.
How can I make the height of the figure smaller, without touching the width, or the text presentation?
The figsize keyword argument can be passed when creating a matplotlib figure using plt.figure() as shown below.
The figsize keyword argument states the figure size in inches. You pass a 2-item tuple of the form (width, height). This allows you to choose the size (and hence aspect ratio) of your figure before you plot any data. Below I have created a figure with width=16in and height=4in.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 1000)
y = np.sin(x)
fig = plt.figure(figsize=(16,4))
ax = fig.add_subplot(1,1,1)
ax.plot(x,y)
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.show()
I would like the following code to produce 4 subplots of the same size with a common aspect ratio between the size of x-axis and y-axis set by me. Referring to the below example, I would like all of the subplots look exactly like the first one (upper left). What is wrong right now is that the size of the y-axis is correlated with its largest value. That is the behaviour I want to avoid.
import matplotlib.pyplot as plt
import numpy as np
def main():
fig = plt.figure(1, [5.5, 3])
for i in range(1,5):
fig.add_subplot(221+i-1, adjustable='box', aspect=1)
plt.plot(np.arange(0,(i)*4,i))
plt.show()
if __name__ == "__main__":
main()
Surprisingly, matplotlib produces the right thing by default (picture below):
import matplotlib.pyplot as plt
import numpy as np
def main():
fig = plt.figure(1, [5.5, 3])
for i in range(1,5):
fig.add_subplot(221+i-1)
plt.plot(np.arange(0,(i)*4,i))
plt.show()
I just want to add to this an ability to control the aspect ratio between lengths of x and y-axes.
I can't quite tell what you want from your question.
Do you want all of the plots to have the same data limits?
If so, use shared axes (I'm using subplots here, but you can avoid it if you want to stick to matlab-style code):
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=2, ncols=2, sharey=True, sharex=True)
for i, ax in enumerate(axes.flat, start=1):
ax.set(aspect=1)
ax.plot(np.arange(0, i * 4, i))
plt.show()
If you want them all to share their axes limits, but to have adjustable='box' (i.e. non-square axes boundaries), use adjustable='box-forced':
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=2, ncols=2, sharey=True, sharex=True)
for i, ax in enumerate(axes.flat, start=1):
ax.set(aspect=1, adjustable='box-forced', xticks=range(i))
ax.plot(np.arange(0, i * 4, i))
plt.show()
Edit: Sorry, I'm still a bit confused. Do you want something like this?
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=2, ncols=2)
for i, ax in enumerate(axes.flat, start=1):
ax.set(adjustable='datalim', aspect=1)
ax.plot(np.arange(0, i * 4, i))
plt.show()
Okay, I think I finally understand your question. We both meant entirely different things by "aspect ratio".
In matplotlib, the aspect ratio of the plot refers to the relative scales of the data limits. In other words, if the aspect ratio of the plot is 1, a line with a slope of one will appear at 45 degrees. You were assuming that the aspect ratio applied to the outline of the axes and not the data plotted on the axes.
You just want the outline of the subplots to be square. (In which case, they all have different aspect ratios, as defined by matplotlib.)
In that case, you need a square figure. (There are other ways, but just making a square figure is far simpler. Matplotlib axes fill up a space that is proportional to the size of the figure they're in.)
import matplotlib.pyplot as plt
import numpy as np
# The key here is the figsize (it needs to be square). The position and size of
# axes in matplotlib are defined relative to the size of the figure.
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8,8))
for i, ax in enumerate(axes.flat, start=1):
ax.plot(np.arange(0, i * 4, i))
# By default, subplots leave a bit of room for tick labels on the left.
# We'll remove it so that the axes are perfectly square.
fig.subplots_adjust(left=0.1)
plt.show()
Combing the answer of Joe Kington with new pythonic style for shared axes square subplots in matplotlib?
and another post that I am afraid I cannot find it again, I made a code for precisely setting the ratio of the box to a given value.
Let desired_box_ratioN indicate the desired ratio between y and x sides of the box.
temp_inverse_axis_ratioN is the ratio between x and y sides of the current plot; since 'aspect' is the ratio between y and x scale (and not axes), we need to set aspect to desired_box_ratioN * temp_inverse_axis_ratioN.
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=2, ncols=2)
desired_box_ratioN = 1
for i, ax in enumerate(axes.flat, start=1):
ax.plot(np.arange(0, i * 4, i))
temp_inverse_axis_ratioN = abs( (ax.get_xlim()[1] - ax.get_xlim()[0])/(ax.get_ylim()[1] - ax.get_ylim()[0]) )
ax.set(aspect = desired_box_ratioN * temp_inverse_axis_ratioN, adjustable='box-forced')
plt.show()
The theory
Different coordinate systems exists in matplotlib. The differences between different coordinate systems can really confuse a lot of people. What the OP want is aspect ratio in display coordinate but ax.set_aspect() is setting the aspect ratio in data coordinate. Their relationship can be formulated as:
aspect = 1.0/dataRatio*dispRatio
where, aspect is the argument to use in set_aspect method, dataRatio is aspect ratio in data coordinate and dispRatio is your desired aspect ratio in display coordinate.
The practice
There is a get_data_ratio method which we can use to make our code more concise. A work code snippet is shown below:
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=2, ncols=2)
dispRatio = 0.5
for i, ax in enumerate(axes.flat, start=1):
ax.plot(np.arange(0, i * 4, i))
ax.set(aspect=1.0/ax.get_data_ratio()*dispRatio, adjustable='box-forced')
plt.show()
I have also written a detailed post about all this stuff here.
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. ax and newax will 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 call fig.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 label kwarg to fig.add_subplot. E.g. newax = fig.add_subplot(111, label='some unique string')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
# If you just call `plt.axes()` or equivalently `fig.add_subplot()` matplotlib
# will just return `ax` again. It _won't_ create a new axis unless we
# call fig.add_axes() or reset fig._seen
newax = fig.add_axes(ax.get_position(), frameon=False)
ax.plot(range(10), 'r-')
newax.plot(range(50), 'g-')
newax.axis('equal')
plt.show()
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...):
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
newax = ax.twiny()
# Make some room at the bottom
fig.subplots_adjust(bottom=0.20)
# I'm guessing you want them both on the bottom...
newax.set_frame_on(True)
newax.patch.set_visible(False)
newax.xaxis.set_ticks_position('bottom')
newax.xaxis.set_label_position('bottom')
newax.spines['bottom'].set_position(('outward', 40))
ax.plot(range(10), 'r-')
newax.plot(range(21), 'g-')
ax.set_xlabel('Red Thing')
newax.set_xlabel('Green Thing')
plt.show()
If you want to have a hidden, unlinked y-axis, and an entirely new x-axis, then you'd do something like this:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
newax = fig.add_axes(ax.get_position())
newax.patch.set_visible(False)
newax.yaxis.set_visible(False)
for spinename, spine in newax.spines.iteritems():
if spinename != 'bottom':
spine.set_visible(False)
newax.spines['bottom'].set_position(('outward', 25))
ax.plot(range(10), 'r-')
x = np.linspace(0, 6*np.pi)
newax.plot(x, 0.001 * np.cos(x), 'g-')
plt.show()
Note that the y-axis values for anything plotted on newax are 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...):
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2, right=0.85)
newax = fig.add_axes(ax.get_position())
newax.patch.set_visible(False)
newax.yaxis.set_label_position('right')
newax.yaxis.set_ticks_position('right')
newax.spines['bottom'].set_position(('outward', 35))
ax.plot(range(10), 'r-')
ax.set_xlabel('Red X-axis', color='red')
ax.set_ylabel('Red Y-axis', color='red')
x = np.linspace(0, 6*np.pi)
newax.plot(x, 0.001 * np.cos(x), 'g-')
newax.set_xlabel('Green X-axis', color='green')
newax.set_ylabel('Green Y-axis', color='green')
plt.show()
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.