Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use matplotlib subplot subgraph

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

Editor to share with you how to use the matplotlib subplot submap, I hope you will gain something after reading this article, let's discuss it together!

Summary

MATLAB and pyplot have the concept of current figure and current axes, and all drawing commands act on the current object. You can get the current axes (axis) through gca () and the current graph (figure) through gcf ().

Import numpy as npimport matplotlib.pyplot as pltdef f (t): return np.exp (- t) * np.cos (2*np.pi*t) T1 = np.arange (0.0,5.0,0.1) T2 = np.arange (0.0,5.0,0.02) plt.figure (1) plt.subplot (211) plt.plot (T1, f (T1), 'bo', T2, f (T2),' K') plt.subplot (212) plt.plot (T2) Np.cos (2*np.pi*t2), 'rmurmuri') plt.show ()

If you do not specify the axis of figure (), the figure (1) command will be created by default, and if you do not specify the axis of subplot (numrows, numcols, fignum), subplot (111) will be created automatically.

Import matplotlib.pyplot as pltplt.figure (1) # create the first artboard (figure) plt.subplot (211) # first subimage of the first artboard plt.plot ([1,2,3]) plt.subplot (212) # second subimage plt.plot ([4,5,6]) plt.figure (2) # create a second artboard plt.plot ([4,5]) 6]) # default subimage command is subplot (111l) plt.figure (1) # call artboard 1 Subplot is still being called plt.subplot (211s) # call subplot (211s) plt.title ('Easy as 1,2,3') # to make the title of 211s

Subplot () divides the entire figure equally, while axes () can draw on the figure.

Import matplotlib.pyplot as pltimport numpy as np# creation data dt = 0.001t = np.arange (0.0,10.0, dt) r = np.exp (- t [: 1000] / 0.05) # impulse responsex = np.random.randn (len (t)) s = np.convolve (x, r) [: len (x)] * dt # colored noise# default spindle graph axes is subplot (111) plt.plot (t, s) plt.axis ([0,1, 1.1*np.amin (s)) 2*np.amax (s)) plt.xlabel ('time (s)') plt.ylabel ('current (nA)') plt.title ('Gaussian colored noise') # inlay a = plt.axes ([.65, .6, .2], facecolor='y') n, bins, patches = plt.hist (s400, normed=1) plt.title (' Probability') plt.xticks ([]) plt.yticks ([]) # another inlay a = plt.axes 0.6, .2, .2], facecolor='y') plt.plot (t [: len (r)], r) plt.title ('Impulse response') plt.xlim (0,0.2) plt.xticks ([]) plt.yticks ([]) plt.show ()

You can clear the current figure with clf () and the current axes with cla (). What you need to pay special attention to is to remember to use close () to close the current figure artboard.

Customize the coordinates of Subplot through GridSpec

GridSpec specifies the geometric mesh on which the subgraph is placed.

SubplotSpec specifies the location of the subgraph (subplot) in the GridSpec.

Subplot2grid is similar to "pyplot.subplot", but it indexes from 0

Ax = plt.subplot2grid ((2jue 2), (0,0)) ax = plt.subplot (2pr 2)

The subplot commands for the above two lines are the same. The commands used by subplot2grid are similar to the HTML language.

Ax1 = plt.subplot2grid ((3jue 3), (0je 0), colspan=3) ax2 = plt.subplot2grid ((3pr 3), (1p 0), colspan=2) ax3 = plt.subplot2grid ((3je 3), (1,2), rowspan=2) ax4 = plt.subplot2grid ((3jue 3), (2,0) ax5 = plt.subplot2grid ((3p3), (2,1))

Use GridSpec and SubplotSpecax = plt.subplot2grid ((2jin2), (0,0))

Equivalent to

Import matplotlib.gridspec as gridspecgs = gridspec.GridSpec (2,2) ax = plt.subplot (gs [0,0])

A gridspec instance provides an array-like index to return the SubplotSpec instance, so we can use slice to merge cells.

Gs = gridspec.GridSpec (3,3) ax1 = plt.subplot (gs [0,:]) ax2 = plt.subplot (gs [1mai Murray 1]) ax3 = plt.subplot (gs [1jue,-1]) ax4 = plt.subplot (gs [- 1jue 0]) ax5 = plt.subplot (gs [- 1mam 2])

Adjust GridSpec layer

When GridSpec is used, you can adjust the parameters of the subplot. This is similar to subplot_adjust, but it only works on GridSpec instances.

Gs1 = gridspec.GridSpec (3,3) gs1.update (left=0.05, right=0.48, wspace=0.05) ax1 = plt.subplot (gs1 [:-1,:]) ax2 = plt.subplot (gs1 [- 1,:-1]) ax3 = plt.subplot (gs1 [- 1,-1]) gs2 = gridspec.GridSpec (3,3) gs2.update (left=0.55, right=0.98, hspace=0.05) ax4 = plt.subplot (gs2 [::-1]) ax5 = plt.subplot (gs2 [:-1) -1]) ax6 = plt.subplot (gs2 [- 1,-1])

Nest GridSpecgs0 = gridspec.GridSpec (1,2) gs00 = gridspec.GridSpecFromSubplotSpec (3,3, subplot_spec=gs0 [0]) gs01 = gridspec.GridSpecFromSubplotSpec (3,3, subplot_spec=gs0 [1]) in subplotSpec

The figure below is an example of a 3-3 square, nested in a 4-4 square.

Resize GridSpec

By default, GridSpec creates cells of the same size. You can adjust the height and width of related rows and columns. Note that the absolute value does not work, the relative value does.

Gs = gridspec.GridSpec (2,2, width_ratios= [1je 2], height_ratios= [4je 1]) ax1 = plt.subplot (gs [0]) ax2 = plt.subplot (gs [1]) ax3 = plt.subplot (gs [2]) ax4 = plt.subplot (gs [3])

Adjust layer

Tigh_layout automatically adjusts the subimage (subplot) parameters to fit the area of the figure. It only checks the scale label (ticklabel), axis label (axis label), and title (title).

The axis (axes) including the subgraph (subplot) is specified by the coordinates of the drawing board (figure). So some tags go beyond the scope of the figure.

Plt.rcParams ['savefig.facecolor'] = "0.8" def example_plot (ax, fontsize=12): ax.plot ([1,2]) ax.locator_params (nbins=3) ax.set_xlabel (' xlyb labelined, fontsize=fontsize) ax.set_ylabel ('Title', fontsize=fontsize) plt.close (' all') fig, ax = plt.subplots () example_plot (ax, fontsize=24)

For subgraphs (subplot), you can solve this problem by adjusting the subplot parameters. Matplotlib v1.1 introduces a new command tight_layout () to solve this problem automatically.

Plt.tight_layout ()

The situation of many subgraphs

Plt.close ('all') fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots (nrows=2, ncols=2) example_plot (ax1) example_plot (ax2) example_plot (ax3) example_plot (ax4)

Plt.tight_layout ()

Tight_layout () contains pad,w_pad and h_pad

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

Using tight_layout () in GridSpec

GridSpec has its own tight_layout () method

Plt.close ('all') fig = plt.figure () import matplotlib.gridspec as gridspecgs1 = gridspec.GridSpec (2,1) ax1 = fig.add_subplot (gs1 [0]) ax2 = fig.add_subplot (gs1 [1]) example_plot (ax1) example_plot (ax2) gs1.tight_layout (fig)

You can specify an optional rect parameter to specify the distance from the subimage (subplot) to the drawing board (figure).

This can also be applied to composite gridspecs.

Gs2 = gridspec.GridSpec (3,1) for ss in gs2:ax = fig.add_subplot (ss) example_plot (ax) ax.set_title ("") ax.set_xlabel (") ax.set_xlabel (" x-label ", fontsize=12) gs2.tight_layout (fig, rect= [0.5,0,1,1], h_pad=0.5)

Use tight_layout () plt.close ('all') fig = plt.figure () from mpl_toolkits.axes_grid1 import Gridgrid = Grid (fig, rect=111, nrows_ncols=, axes_pad=0.25, label_mode='L',) for ax in grid:example_plot (ax) ax.title.set_visible (False) plt.tight_layout () in AxesGrid1

Using tight_layout () in colorbar

Colorbar is an instance of Axes, not an instance of Subplot, so tight_layout doesn't work. In matplotlib v1.1, you use colorbar as a subplot to use gridspec.

Plt.close ('all') arr = np.arange. Reshape fig = plt.figure (figsize= (4,4)) im = plt.imshow (arr, interpolation= "none") plt.colorbar (im, use_gridspec=True) plt.tight_layout ()

Another way is to use the AxesGrid1 toolkit to create an axis Axes for colorbar

Plt.close ('all') arr = np.arange. Reshape fig = plt.figure (figsize= (4,4)) im = plt.imshow (arr, interpolation= "none") from mpl_toolkits.axes_grid1 import make_axes_locatabledivider = make_axes_locatable (plt.gca () cax= divider.append_axes ("right", "5", pad= "3") plt.colorbar (im, cax=cax) plt.tight_layout ()

After reading this article, I believe you have a certain understanding of "how to use matplotlib subplot subimages". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report