I am using the python graphing library matplotlib to graph several things in a report, and I found myself needing to have several fixed-count graphs above an arbitrary grid of smaller graphs. I searched around, but was unable to find anything that would let me use two gridspec layouts on a single matplotlib figure. What I want essentially:
I know I could hack some solution if the number of graphs per row in the second group is an even number. but if each row has an odd count, then such a solution is not possible. For example, imagine I have 5 graphs per row in the small graph section, then it would be impossible to have two equal size graphs side by side above them, and the gridspec does not let you specify fractional indices(and it shouldn't).
In my mind the proper solution would be to have two separate gridspec layouts on the single figure, one for the fixed count graphs on the top half, and then a programmatically scaled gridspec for the smaller graphs on the bottom half. I have found no such solution in matplotlib with gridspec or subplots, so does anyone have any suggestions for such a graph setup using matplotlib?
To draw multiple plots using the subplot() function from the pyplot module, you need to perform two steps: First, you need to call the subplot() function with three parameters: (1) the number of rows for your grid, (2) the number of columns for your grid, and (3) the location or axis for plotting.
plt. subplots() , created a grid (2 rows and 3 columns). The function returned the figure object (stored in fig ) that will hold all the subplots, as well as all the individual axes (stored in axes ).
Matplotlib's matplotlib.gridspec
module contains a class called gridspec.GridSpecFromSubplotSpec
. Like gridspec.GridSpec
, it takes nrow and ncols parameters which allow you to specify the cells that subplots will occupy/span, however it also requires a SubplotSpec
object, which can be a cell or cell span from a GridSpec
object. The returned object is a GridSpec
which is dependent on the cell dimensions of the SubplotSpec
that was used to create it.
Example:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
outer_grid = gridspec.GridSpec(1,2) # gridspec with two adjacent horizontal cells
left_cell = outer_grid[0,1] # the left SubplotSpec within outer_grid
inner_grid = gridspec.GridSpecFromSubplotSpec(2,1, left_cell)
# From here we can plot usinginner_grid's SubplotSpecs
ax1 = plt.subplot(inner_grid[0,0])
ax2 = plt.subplot(inner_grid[1,0])
ax1.plot(data)
ax2.plot(other_data)
plt.show()
The result of this code is:
---------------------------------
| |---------------|
| We didn't plot| | |other| |
| anything here.| |data |data | |
| | | | | |
| |---------------|
---------------------------------
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With