This question already has answers here:
Matplotlib different size subplots
(6 answers)
Closed 1 year ago.
I have a script which is creating one or two charts, depending on if one specific condition is met or not. Really basically, what I am doing so far is the following:
import matplotlib.pyplot as plt
list1 = [1,2,3,4]
list2 = [4,3,2,1]
somecondition = True
plt.figure(1) #create one of the figures that must appear with the chart
ax = plt.subplot(211) #create the first subplot that will ALWAYS be there
ax.plot(list1) #populate the "main" subplot
if somecondition == True:
ax = plt.subplot(212) #create the second subplot, that MIGHT be there
ax.plot(list2) #populate the second subplot
plt.show()
This code (with the proper data, but this simple version that I did is executable anyway) generates two subplots of the same size, one above the other. However, what I would like to get is the following:
If somecondition is True, then both subplots should appear in the figure. Hence, I would like the second subplot to be 1/2 smaller than the first one;
If somecondition is False, then just the first subplot should appear and I would like it to be sized as the all figure (without leaving the empty space behind in the case the second subplot will not appear).
I'm pretty sure it's just a matter of sizing the two subplots, probably even by the parameter 211 and 212 (that I don't understand what they stand for, since I'm new to Python and couldn't find a clear explanation on the web yet). Does anyone know how to regulate the size of the subplots in a easy way, proportionally to the number of subplots as well as to the entire size of the figure? To make it easier to understand, could you also please edit my simple code I attached to get the result I'm looking for? Thanks in advance!
does this solution satisfy?
import matplotlib.pyplot as plt
list1 = [1,2,3,4]
list2 = [4,3,2,1]
somecondition = True
plt.figure(1) #create one of the figures that must appear with the chart
if not somecondition:
ax = plt.subplot(111) #create the first subplot that will ALWAYS be there
ax.plot(list1) #populate the "main" subplot
else:
ax = plt.subplot(211)
ax.plot(list1)
ax = plt.subplot(223) #create the second subplot, that MIGHT be there
ax.plot(list2) #populate the second subplot
plt.show()
If you need the same width but with half height, better to use matplotlib.gridspec, reference here
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
list1 = [1,2,3,4]
list2 = [4,3,2,1]
somecondition = True
plt.figure(1) #create one of the figures that must appear with the chart
gs = gridspec.GridSpec(3,1)
if not somecondition:
ax = plt.subplot(gs[:,:]) #create the first subplot that will ALWAYS be there
ax.plot(list1) #populate the "main" subplot
else:
ax = plt.subplot(gs[:2, :])
ax.plot(list1)
ax = plt.subplot(gs[2, :]) #create the second subplot, that MIGHT be there
ax.plot(list2) #populate the second subplot
plt.show()
It seems you are looking for this:
if somecondition:
ax = plt.subplot(3,1,(1,2))
ax.plot(list1)
ax = plt.subplot(3,1,3)
ax.plot(list2)
else:
plt.plot(list1)
The magic numbers are nrows, ncols, plot_number, see the documentation. So 3,1,3 will create 3 rows, 1 column, and will plot into the third cell. An abbreviation for that is 313.
It's possible to use tuple as plot_number, so you can create a plot which lives in the first and second cell: 3,1,(1,2).
Related
I have 5 graphs. My code continue with this way:
plots = zip(x,y)
def loop_plot(plots):
figs = {}
axs = {}
for idx, plot in enumerate(plots):
figs[idx] = plt.figure()
axs[idx] = figs[idx].add_subplot(111)
axs[idx].plot(plot[0],plot[1])
return figs, axs
figs,axs=loop_plot(plots)
This code create 5 different graph. BUt I would like to plot 5 graph in one figure. I mean, I would like to create 5 different figure into one code. How can I manage it? I have 5 different x and y dataset. how can I write subplot code with for loop?
You have to be careful about using the terms figure and axes when talking about matplotlib, as they mean slightly different things to normal English usage. An axes object is a pair of (x,y) axes, and a figure is a container that holds one or more axes. The reason I say that is because the code to solve your problem will be different if you want five different lines on one set of axes, or if you want one figure containing 5 separate axis, each with one line.
5 separate axes
def loop_plot1(plots):
shape = (2, 3) # Fix this to make it more general if you want to handle more than 6 plots!
list_ax = []
fig = plt.figure()
for i, plot in enumerate(plots):
idx = i + 1
list_ax.append(fig.add_subplot(shape[0], shape[1], idx)) # a more general way of writing, eg, add_subplot(231) etc.
list_ax[i].plot(plot[0], plot[1])
loop_plot1(plots)
5 lines on one axes
def loop_plot2(plots):
shape = (2, 3) # Fix this to make it more general if you want to handle more than 6 plots!
fig, ax = plt.subplots() # implicitly does fig = plot.figure() // fig.add_subplot(111)
for i, plot in enumerate(plots):
ax.plot(plot[0], plot[1])
loop_plot2(plots)
How do I prevent matplotlib from adding default axis labels to my subplot? The simple code below also labels the x and y axes for 0 to 1. This is messing up my plot when I add actual data (the new labels are added according to the data but the 0 to 1 labels are still present).
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax1 = fig.add_subplot(111)
plt.show(block=True)
The above produces this figure:
So when I include actual data it looks like this, with just this additional line of code (final_wavelengths and final_stellar are numpy arrays of equal length):
ax1.plot(final_wavelengths, final_stellar, 'b', label='stellar')
How can I remove the unwanted default 0-1 labels?
I was pointed to similar issue. for me worked explicit assigning to right axes by using ax = fig.axes[0] (I had a list of 2 different axes and needed for work just the first one)
I am plotting 20+ features like so:
for col in dsd_mod["ae_analysis"].columns[:len(dsd_mod["ae_analysis"].columns)]:
if col != "sae_flag":
sns.distplot(dsd_mod["ae_analysis"].loc[(dsd_mod["ae_analysis"]['sae_flag'] == 1),col],
color='r',
kde=True,
hist=False,
label='sae_ae = 1')
sns.distplot(dsd_mod["ae_analysis"].loc[(dsd_mod["ae_analysis"]['sae_flag'] == 0),col],
color='y',
kde=True,
hist=False,
label='sae_ae = 0')
Which creates a separate graph for each feature. How can I put these all on a matrix? Or like how pair plots outputs?
Right now I get 30 graphs like this all in one column:
How can I modify this so that I can get 6 rows and 5 columns ?
Thanks in advance!
displot can use whatever axes object you want to draw the plot. So you just need to create your axes with the desired geometry, and pass the relevant axes to your functions.
fig, axs = plt.subplots(6,5)
# axs is a 2D array with shape (6,5)
# you can keep track of counters in your for-loop to place the resulting graphs
# using ax=axs[i,j]
# or an alternative is to use a generator that you can use to get the next axes
# instance at every step of the loop
ax_iter = iter(axs.flat)
for _ in range(30):
ax = next(ax_iter)
sns.distplot(np.random.normal(loc=0, size=(1000,)), ax=ax)
sns.distplot(np.random.normal(loc=1, size=(1000,)), ax=ax)
I have following graph:
However, I want that graphs 221 and 223 share the same x axis. I have the following code:
self.fig_part_1 = plt.figure()
self.plots_part_1 = [
plt.subplot(221),
plt.subplot(223),
plt.subplot(122),
]
How can I achieve that? In the end I do not want the numbers of axis x in plot 221 to be shown.
(This is mostly a comment to #H. Rev. but I post it as an "answer" to get nicer code formatting)
I think it is way better to just add the subplots manually, since as you implemented it now it will give two axes that you just throw away. They might even give problems with overlapping axis-ticks and a lot of confusion in general. I believe it is better to create the figure first, and then add axes one by one. This way also solves the problem by having to "update" the current figure with plt.figure(self.f.number) since you have direct access to e.g. fig_N
import matplotlib.pyplot as plt
fig1 = plt.figure()
# fig2 = plt.figure() # more figures are easily accessible
# fig3 = plt.figure() # more figures are easily accessible
ax11 = fig1.add_subplot(221) # add subplot into first position in a 2x2 grid (upper left)
ax12 = fig1.add_subplot(223, sharex=ax11) # add to third position in 2x2 grid (lower left) and sharex with ax11
ax13 = fig1.add_subplot(122) # add subplot to cover both upper and lower right, in a 2x2 grid. This is the same as the rightmost panel in a 1x2 grid.
# ax21 = fig2.add_subplot(211) # add axes to the extra figures
# ax21 = fig2.add_subplot(212) # add axes to the extra figures
# ax31 = fig3.add_subplot(111) # add axes to the extra figures
plt.show()
Just use plt.subplots (different from plt.subplot) to define all your axes, with the option sharex=True:
f, axes = plt.subplots(2,2, sharex=True)
plt.subplot(122)
plt.show()
Note that the second call with larger subplot array overlay the preceding one.
Example (could not display image due to reputation...)
I want to create a plot consisting of several subplots with shared x/y axes.
It should look something like this from the documentation (though my subplots will be scatterblots): (code here)
But I want to create the subplots dynamically!
So the number of subplots depends on the output of a previous function. (It will probably be around 3 to 15 subplots per diagram, each from a distinct dataset, depending on the input of my script.)
Can anyone tell me how to accomplish that?
Suppose you know total subplots and total columns you want to use:
import matplotlib.pyplot as plt
# Subplots are organized in a Rows x Cols Grid
# Tot and Cols are known
Tot = number_of_subplots
Cols = number_of_columns
# Compute Rows required
Rows = Tot // Cols
# EDIT for correct number of rows:
# If one additional row is necessary -> add one:
if Tot % Cols != 0:
Rows += 1
# Create a Position index
Position = range(1,Tot + 1)
First instance of Rows accounts only for rows completely filled by subplots, then is added one more Row if 1 or 2 or ... Cols - 1 subplots still need location.
Then create figure and add subplots with a for loop.
# Create main figure
fig = plt.figure(1)
for k in range(Tot):
# add every single subplot to the figure with a for loop
ax = fig.add_subplot(Rows,Cols,Position[k])
ax.plot(x,y) # Or whatever you want in the subplot
plt.show()
Please note that you need the range Position to move the subplots into the right place.
import matplotlib.pyplot as plt
from pylab import *
import numpy as np
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
subplots_adjust(hspace=0.000)
number_of_subplots=3
for i,v in enumerate(xrange(number_of_subplots)):
v = v+1
ax1 = subplot(number_of_subplots,1,v)
ax1.plot(x,y)
plt.show()
This code works but you will need to correct the axes. I used to subplot to plot 3 graphs all in the same column. All you need to do is assign an integer to number_of_plots variable. If the X and Y values are different for each plot you will need to assign them for each plot.
subplot works as follows, if for example I had a subplot values of 3,1,1. This creates a 3x1 grid and places the plot in the 1st position. In the next interation if my subplot values were 3,1,2 it again creates a 3x1 grid but places the plot in the 2nd position and so forth.
Based on this post, what you want to do is something like this:
import matplotlib.pyplot as plt
# Start with one
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3])
# Now later you get a new subplot; change the geometry of the existing
n = len(fig.axes)
for i in range(n):
fig.axes[i].change_geometry(n+1, 1, i+1)
# Add the new
ax = fig.add_subplot(n+1, 1, n+1)
ax.plot([4,5,6])
plt.show()
However, Paul H's answer points to the submodule called gridspec which might make the above easier. I am leaving that as an exercise for the reader ^_~.
Instead of counting your own number of rows and columns, I found it easier to create the subplots using plt.subplots first, then iterate through the axes object to add plots.
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(12, 8))
x_array = np.random.randn(6, 10)
y_array = np.random.randn(6, 10)
i = 0
for row in axes:
for ax in row:
x = x_array[i]
y = y_array[i]
ax.scatter(x, y)
ax.set_title("Plot " + str(i))
i += 1
plt.tight_layout()
plt.show()
Here I use i to iterate through elements of x_array and y_array, but you can likewise easily iterate through functions, or columns of dataframes to dynamically generate graphs.