Using pyplot to create grids of plots

2024/10/15 23:25:28

I am new to python and having some difficulties with plotting using pyplot. My goal is to plot a grid of plots in-line (%pylab inline) in Juypter Notebook.

I programmed a function plot_CV which plots cross-validation erorr over the degree of polynomial of some x where across plots the degree of penalization (lambda) is supposed to vary. Ultimately there are 10 elements in lambda and they are controlled by the first argument in plot_CV. So

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1) 
ax1 = plot_CV(1,CV_ve=CV_ve)

Gives

enter image description here

Now I think I have to use add_subplot to create a grid of plots as in

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1 = plot_CV(1,CV_ve=CV_ve)
ax2 = fig.add_subplot(2,2,2)
ax2 = plot_CV(2,CV_ve=CV_ve)
ax3 = fig.add_subplot(2,2,3)
ax3 = plot_CV(3,CV_ve=CV_ve)
ax4 = fig.add_subplot(2,2,4)
ax4 = plot_CV(4,CV_ve=CV_ve)
plt.show()

enter image description here

If I continue this, however, then the plots get smaller and smaller and start to overlap on the x and y labels. Here a picture with a 3 by 3 plot.

enter image description here

Is there a way to space the plots evenly, so that they do not overlap and make better use of the horizontal and vertical in-line space in Jupyter Notebook? To illustrate this point here a screenshot from jupyter:

enter image description here

Final note: I still need to add a title or annotation with the current level of lambda used in plot_CV.


Edit: Using the tight layout as suggested, gives:

enter image description here


Edit 2: Using the fig.set_figheight and fig.set_figwidth I could finally use the full length and heigth available.

enter image description here

Answer

The first suggestion to your problem would be taking a look at the "Tight Layout guide" for matplotlib.

They have an example that looks visually very similar to your situation. As well they have examples and suggestions for taking into consideration axis labels and plot titles.

Furthermore you can control the overall figure size by using Figure from the matplotlib.figure class.

Figure(figsize = (x,y))figsize: x,y (inches)

EDIT:

Here is an example that I pulled from the matplotlib website and added in the:

fig.set_figheight(15)
fig.set_figwidth(15)

example:

import matplotlib.pyplot as pltplt.rcParams['savefig.facecolor'] = "0.8"def example_plot(ax, fontsize=12):ax.plot([1, 2])ax.locator_params(nbins=3)ax.set_xlabel('x-label', fontsize=fontsize)ax.set_ylabel('y-label', fontsize=fontsize)ax.set_title('Title', fontsize=fontsize)plt.close('all')
fig = plt.figure()fig.set_figheight(15)
fig.set_figwidth(15)ax1 = plt.subplot2grid((3, 3), (0, 0))
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)plt.tight_layout()

You can achieve padding of your subplots by using tight_layout this way:

plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)

That way you can keep your subplots from crowding each other even further.

Have a good one!

https://en.xdnf.cn/q/69225.html

Related Q&A

matplotlib: deliberately block code execution pending a GUI event

Is there some way that I can get matplotlib to block code execution pending a matplotlib.backend_bases.Event?Ive been working on some classes for interactively drawing lines and polygons inside matplo…

Connecting Keras models / replacing input but keeping layers

This questions is similar to Keras replacing input layer. I have a classifier network and an autoencoder network and I want to use the output of the autoencoder (i.e. encoding + decoding, as a preproce…

PySpark 2.x: Programmatically adding Maven JAR Coordinates to Spark

The following is my PySpark startup snippet, which is pretty reliable (Ive been using it a long time). Today I added the two Maven Coordinates shown in the spark.jars.packages option (effectively "…

Python: How to create simple web pages without a huge framework? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, argum…

AttributeError: module MySQLdb.constants.FIELD_TYPE has no attribute JSON while migrating in Django

I do not know in what way solve this error. Any hints? I have simple Django projects and receive this error when try to do python3 manage.py migrate. This is related to any programming error in app or…

Downloading file using IE from python

Im trying to download file with Python using IE:from win32com.client import DispatchWithEventsclass EventHandler(object):def OnDownloadBegin(self):passie = DispatchWithEvents("InternetExplorer.App…

Good resources to start python for web development?

Im really interested in learning Python for web development. Can anyone point me in the right direction? Ive been looking at stuff on Google, but havent really found anything that shows proper documen…

django file upload: [Errno 13] Permission denied: /static

I am trying to upload several files in django. On my local maching where I use the djangos build in server everything works fine but on my productivity server I get this error:[Errno 13] Permission den…

efficient way to change the header of a file in Python

I am trying to write a python script to update the header (only the first line) of some huge files, but as the new header is not necessary to be the same size (in bytes) as the original one, is there a…

Converting a numpy array of dtype objects to dtype complex

I have a numpy array which I want to convert from an object to complex. If I take that array as dtype string and convert it, there is no problem:In[22]: bane Out[22]: array([1.000027337501943-7.3310852…