Making an odd number of subplots in Python - python

I'm very new to Python, and I want to plot 13 different figures all in one plot. To do this nicely, I would like to plot the first 12 figures in a 6x2 grid (this works just fine), and then plot the 13th figure below it; either the same size as the other figures and centered, or larger than the rest so that its width is equal to twice the width of the other figures and all the edges are aligned. What would be the best way to specify axes of this kind using subplots? (So far, I've just used nrows=6, ncols=2, but I think something like that won't work with an odd number of figures to plot.) The code I have so far for plotting the first 12 plots looks like this (with simple test data):
fig, axes = plt.subplots(nrows=6, ncols=2, figsize=(45,10))
for ax in axes.flat:
ax.plot([1,2,3,4])
fig.subplots_adjust(right=0.5)
How can I add a 13th figure below the others?

You can use GridSpec (link to documentation) to generate flexible axes layout.
The following code creates the desired layout and puts all Axes objects in a list for easy access.
gs00 = matplotlib.gridspec.GridSpec(7, 2)
fig = plt.figure()
axs = []
for i in range(6):
for j in range(2):
ax = fig.add_subplot(gs00[i,j])
axs.append(ax)
ax = fig.add_subplot(gs00[6,:])
axs.append(ax)

Related

python matplotlib mulitple figures (not subplots) on same pdf with custom arrangment

I have a collection of charts I need to put on the same pdf, but they are grouped into different subplot grids like below.
Ex. I have something like
fig, axes = plt.subplots(num_rows, num_cols)
fig2, axes2 = plt.subplots(num_rows2, num_cols2)
fig3, axes3 = plt.subplots(num_rows3, num_cols3)
# more figures
I'm trying a find a way of arranging the figures in the the pdf in a custom way, similar to what you can do with subplots,
fig, axis = plt.subplots(rows, cols)
axis[0, 0].plot(X, Y)
axis[0, 1].plot(X2, Y2)
but instead of a grid of axises it would be a grid of figures, and I could tell matplotlib which row or column each figure goes in.
Is there a way to do this? One workaround is to just have one figure and calculate the positions of all the plots manually based on which group there are in, but I'm wondering if there's something built in to matplotlib to do this.

Matplotlib: How to extract vlines and fill_between data from ax objects?

I have a figure comprised of two x/y curves, a vline and a fill_between in Matplotlib.
My ultimate aim is displaying this figure along with 2 other figures as subplots in a 4th new figure. And I really want to avoid creating all three figures from scratch again just for this new figure with subplots.
So, I'm looking to create a 1x3 figure (subplots, 1 row, 3 columns) like this:
[fig1, fig2, fig3]
I'm almost there. I've so far been able to extract the two x/y curves from the original figure's ax object. Moving through a for loop, I've been able to rebuild most of the three figures as subplots in my new figure:
(ax_a, ax_b, ax_c are ax objects belonging to the three original figures I want to add as subplots to my new figure)
fig = plt.figure(figsize = (16,4))
ax1 = fig.add_subplot(1,3,1)
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)
for ax, ref in zip(fig.axes, [ax_a, ax_b, ax_c]):
for line in ref.lines:
x = line.get_xdata()
y = line.get_ydata()
ax.plot(x,y)
ax.set_xlabel(ref.get_xlabel())
ax.set_ylabel(ref.get_ylabel())
This actually creates a 1x3 grid of my original 3 plots. It's almost perfect.
What's missing are the fill_between component and the vlines component. If I could extract those objects from ax_a, ax_b and ax_c, I'd be done. But I can't find a way to do that.
Is there a way? If not, how would you solve a problem like this?
Thanks so much in advance for any advice offered.

How to remove the extra figures created when running a for loop to create seaborn plots

I am trying to do EDA along with exploring the Matplotlib and Seaborn libraries.
The data_cat DataFrame has 4 columns and I want to create plots in a single row with 4 columns.
For that, I created a figure object with 4 axes objects.
fig, ax = plt.subplots(1,4, figsize = (16,4))
for i in range(len(data_cat.columns)):
sns.catplot(x = data_cat.columns[i], kind = 'count', data = data_cat, ax= ax[i])
The output for it is a figure with the 4 plots (as required) but it is followed by 4 blank plots that I think are the extra figure objects generated by the sns.catplot function.
Your code does not work as intended because sns.catplot() is a figure level function, that is designed to create its own grid of subplots if desired. So if you want to set up the subplot grid directly in matplotlib, as you do with your first line, you should use the appropriate axes level function instead, in this case sns.countplot():
fig, ax = plt.subplots(1, 4, figsize = (16,4))
for i in range(4):
sns.countplot(x = data_cat.columns[i], data = data_cat, ax= ax[i])
Alternatively, you could use pandas' df.melt() method to tidy up your dataset so that all the values from your four columns are in one column (say 'col_all'), and you have another column (say 'subplot') that identifies from which original column each value is. Then you can get all the subplots with one call:
sns.catplot(x='col_all', kind='count', data=data_cat, col='subplot')
I answered a related question here.

Is there a way in python using matplotlib to create a figure with subplots of subplots?

I'm trying to display a figure that contains 3 plots, and each of the plots is a plot of (8,1)-shaped subplots.
Essentially, I want one big figure with three sections each containing (8,1)-shaped subplots.
I'm looking for a way to do this without having to manually set all the proportions and spacings. The reason I'm doing this is to visualize an 8-channel neural signal compared to three other pre-defined signals, each signal being 8 channels.
If it makes any sense this way, I'm trying for something like this (ficticious code):
fig, ax = plt.subplots(n_figures = 3, n_rows = 8, n_cols = 1)
ax[figure_i, row_j, col_k].imshow(image)
Is there a way to do this?
Here is an example of what I am talking about. Ideally it would three subplots, and in each of the subplots there is a set of subplots of shape 8x1. I understand how to plot this all out by going through all the margins and setting the proportions, but I'm wondering if there's a simpler way to do this without having to go through all the additional code and settings as described in the above example code I've written.
You can create this kind of figure by first creating a subplot grid with the appropriate layout using the plt.subplots() function and then looping through the array of axes to plot the data, like in this example:
import numpy as np # v 1.19.2
import matplotlib.pyplot as plt # v 3.3.2
# Create sample signal data as a 1-D list of arrays representing 3x8 channels
signal_names = ['X1', 'X2', 'X3']
nsignals = len(signal_names) # ncols of the subplot grid
nchannels = 8 # nrows of the subplot grid
nsubplots = nsignals*nchannels
x = np.linspace(0, 14*np.pi, 100)
y_signals = nsubplots*[np.cos(x)]
# Set subplots width and height
subp_w = 10/nsignals # 10 corresponds the figure width in inches
subp_h = 0.25*subp_w
# Create figure and subplot grid with the appropriate layout and dimensions
fig, axs = plt.subplots(nchannels, nsignals, sharex=True, sharey=True,
figsize=(nsignals*subp_w, nchannels*subp_h))
# Optionally adjust the space between the subplots: this can also be done by
# adding 'gridspec_kw=dict(wspace=0.1, hspace=0.3)' to the above function
# fig.subplots_adjust(wspace=0.1, hspace=0.3)
# Loop through axes to create plots: note that the list of axes is transposed
# in this example to plot the signals one after the other column-wise, as
# indicated by the colors representing the channels
colors = nsignals*plt.get_cmap('tab10').colors[:nchannels]
for idx, ax in enumerate(axs.T.flat):
ax.plot(x, y_signals[idx], c=colors[idx])
if ax.is_first_row():
ax.set_title(signal_names[idx//nchannels], pad=15, fontsize=14)
plt.show()

Python: Parallel coordinates subplots in subplot

I saw this example on how to create a parallel coordinate plot: Parallel Coordinates:
This creates a nice Parallel Coordinates figure, but I would like to add this plot to an already existing figure in a subplot (there should be another plot next to it in the same plot).
For the already existing figure, the figure and axes are defined as:
fig = plt.figure(figsize=plt.figaspect(2.))
ax = fig.add_subplot(1,2,1)
For the Parallel Coordinates, they suggest:
fig, axes = plt.subplots(1, dims-1, sharey=False)
How can I reconcile both initializations of the figure and the ax(es)?
One option is to create all the axes using subplots then just shift the location of the one that you don't want to have wspace=0 as is done for the Parallel Coordinate plots:
import matplotlib.pylab as plt
dims = 4
fig, axes = plt.subplots(1, dims-1 + 1, sharey=False)
plt.subplots_adjust(wspace=0)
ax1 = axes[0]
pos = ax1.get_position()
ax1.set_position(pos.translated(tx = -0.1,ty=0))
I have added 1 to the number of columns creates (leaving it explicitly -1+1) and set wspace=0 which draws all the plots adjacent to one another with no space inbetween. Take the left most axes and get the position which is a Bbox. This is nice as it gives you the ability to translate it by tx=-0.1 separating your existing figure.

Categories