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

What are the common uses of Matplotlib

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces what are the common uses of Matplotlib. It is very detailed and has certain reference value. Friends who are interested must finish it!

1. Common usage of Matplotlib 1. Draw a simple image

Let's take the most common activation function sigmoid in machine learning as an example, and let's draw it.

Import matplotlib.pyplot as pltimport numpy as npx = np.linspace (- 1010 np.exp 1000) y = 1 / (1 + np.exp (- x)) plt.plot (xmemy) plt.show ()

The formula of sigmoid is: $y = f (x) =\ frac {1} {1 + e ^ {- x}} $plot () method shows the trend between variables, show () method shows the image.

We get the image shown in the figure:

two。 Add common elements

We add some reference elements, and the interpretation of each function is annotated in detail in the code.

X = np.linspace (- 1010 np.exp (- x)) # write formula y = 1 / (1 + np.exp (- x)) # x axis range limit plt.xlim (- 5pm 5) # y axis range limit plt.ylim (- 0.2pm 1.2) # x axis tagging plt.xlabel ("X axis") # y axis tagging plt.ylabel ("Y axis") # title plt.title ("sigmoid function") # set grid The red dotted line plt.grid (line, color= "red") # sets the horizontal reference line plt.axhline (yearly 0.5, color= "green", line, linewidth=2) # sets the vertical guide line plt.axvline (xcam0.0, color= "green", line, linewidth=2) # draws the curve plt.plot (xMagin y) # saves the image plt.savefig (". / sigmoid.png", format='png', dpi=300)

The above code includes limiting the range of X and Y axes, adding titles and labels, setting grids, adding guides, saving images, and so on.

Draw the image as follows:

3. Draw multiple curves # generate 1000 values uniformly distributed x = np.linspace (- 10 np.exp (- 1)) # write sigmoid formula y = 1 / (1 + 10 (- x)) z = x**2plt.xlim (- 2) plt.ylim (0L1) # draw sigmoidplt.plot (XMague colorific colors, E0BF1D colors, label = "sigmoid") # draw y=x*xplt.plot (XMZ colors, purposeful colors, linestyleurs, colors, etc.) # draw legend The legend plt.legend (loc= "upper left") # in the corner below shows plt.show ()

Draw multiple images and directly call multiple plot (). Note: if you do not call the legend () method, the legend (legend) in the upper-left corner will not be drawn. The color parameter supports hex representation.

4. Know figure (canvas)

First of all, we know figure (canvas), such as legend, which we mentioned above, is the display of line tags. The dotted lines enclosed by grid are grid guides. Text tags such as Title/x axislabel. This picture helps us to have a value-based understanding of figure.

5. Draw multiple images

One figure can correspond to multiple plot, so now let's try to draw multiple images on one figure.

X = np.linspace (- 2*np.pi, 2*np.pi, 400y) y = np.sin (xcamel 2) z = 1 / (1 + np.exp (- x)) a = np.random.randint (0100400) b = np.maximum (xmeme 0.1mm x) # create two rows and two columns of sub-image fig, ax_list = plt.subplots (nrows=2, ncols=2) # 'rmuri' where r represents color=red -denotes linestyle='-'ax_list [0] [0] .plot [0] [0] .title.set _ text ('sin') ax_list [0] [1] .plot [0] [1] .title.set _ text (' scatter') ax_list [1] [0] .plot 'bmur.') ax_list [1] [0] .title.set _ text ('leaky relu') ax_list [1] [1] .plot (Xmeme Zhonag') ax_list [1] [1] .title.set _ text (' sigmoid') # adjust the layout of the subimage fig.subplots_adjust (wspace=0.9,hspace=0.5) fig.suptitle ("Figure graphs", fontsize=16)

Among them, the most critical is the subplots method, which generates 2 rows and 2 columns of sub-images, and then we call each drawing method in ax_list. One of them is' rmelight', which is called 'rmelight'. The parameter is the abbreviation of drawing, which will be explained separately in the following paragraph of parameter abbreviation in this article.

6. Draw a common map

We often use graphs to represent the relationship between data, including histogram, histogram, pie chart, scatter chart and so on.

# make the drawing support Chinese plt.rcParams ['font.sans-serif'] = [' Microsoft YaHei'] # create two rows and two columns of sub-image fig, [[ax1,ax2], [ax3,ax4], [ax5,ax6]] = plt.subplots (nrows=3, ncols=2,figsize= (8d8)) # draw a bar chart barvalue = (2,3,4,1,2) index = np.arange (5) ax1.bar (index, value,alpha=0.4) Color='b') ax1.set_xlabel ('Group') ax1.set_ylabel (' Scores') ax1.set_title ('histogram') # draw histogram histogramh = 100 + 15 * np.random.randn (437) ax2.hist (h, bins=50) ax2.title.set_text ('histogram') # draw pie pielabels = 'Frogs',' Cai', 'Yongji',' Logs'sizes = [15,30,45,10] explode = (0,0.1,0) 0) ax3.pie (sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax3.axis ('equal') # Equal aspect ratio ensures that pie is drawn as a circle.ax3.title.set_text (' pie') # draw cotton swabs stemx = np.linspace (0.5, 2*np.pi, 20) y = np.random.randn (20) ax4.stem (xQuery y, linefmt= "-.", markerfmt= "o") Basefmt='-') ax4.set_title ("cotton stick diagram") # draw bubble diagram scattera = np.random.randn (100b) b = np.random.randn (100ax5.scatter (a, b, s=np.power), c=np.random.rand (100th), cmap=plt.cm.RdYlBu, marker= "o") # draw pole diagram polarfig.delaxes (ax6) ax6 = fig.add_subplot (236, projection='polar') # ax6 = fig.add_subplot Projection='polar') # 2 line 3 columns, sixth figure r = np.arange (0,2,0.01) theta = 2 * np.pi * rax6.plot (theta, r) ax6.set_rmax (2) ax6.set_rticks ([0.5,1,1.5,2]) # Less radial ticksax6.set_rlabel_position (- 22.5) # Move radial labels away from plotted lineax6.grid (True) # adjust the layout of the sub-image fig.subplots_adjust (wspace=1,hspace=1.2) fig.suptitle ("drawing", fontsize=16)

Draw the image as follows:

7. Parameter abbreviation

Because matplotlib supports abbreviations for parameters, I think it is necessary to talk about the abbreviations of each parameter separately.

X = np.linspace (- 1010 np.exp (- 20)) y = 1 / (1 + np.exp (- x)) plt.plot (x recorder) plt.legend ()

Draw the image as follows:

7.1c for color (color) character color 'b'blue'g'green'r'red'c'cyan'm'magenta'y'yellow'k'black'w'white7.2 ls for linestyle (line style) character description'-'solid linestyle'-- 'dashed linestyle' -. 'dash-dot linestyle': 'dotted linestyle'. 'point marker' 'pixel marker'o'circle marker'v'triangle_down marker' ^' triangle_up marker''triangle_right marker'1'tri_down marker'2'tri_up marker'3'tri_left marker'4'tri_right marker's'square marker'p'pentagon marker'*'star marker'h'hexagon1 marker'H'hexagon2 marker'+'plus marker'x'x marker'D'diamond marker'd'thin_diamond marker' | 'vline marker'_'hline marker7.3 marker (tick style)

The tick style is shown as follows:

7.4 other abbreviations

Lw stands for linewidth (line width), such as lw=2.5

Ms stands for markersize (tick size), such as ms=5

Mfc stands for markerfacecolor (tick color), such as mfc='red'

Second, the advanced usage of Matplotlib 1. Add text comment

We can add text, arrows and other annotations to the canvas (figure) to make the image more clear and accurate.

We draw comments by calling the annotate method.

Fig, ax = plt.subplots (figsize= (8,8)) t = np.arange (0.0,5.0,0.01) s = np.cos (2*np.pi*t) # draw a curve line, = ax.plot (t, s) # add comments ax.annotate ('figure pixels', xy= (10,10), xycoords='figure pixels') ax.annotate (' figure points', xy= (80,80) Xycoords='figure points') ax.annotate ('figure fraction', xy= (.025, .975), xycoords='figure fraction', horizontalalignment='left', verticalalignment='top', fontsize=20) # first arrow ax.annotate (' point offset from data', xy= (2,1), xycoords='data', xytext= (- 15,25), textcoords='offset points', arrowprops=dict (facecolor='black') Shrink=0.05), horizontalalignment='right', verticalalignment='bottom') # second arrow ax.annotate ('axes fraction', xy= (3,1), xycoords='data', xytext= (0.8,0.95), textcoords='axes fraction', arrowprops=dict (facecolor='black', shrink=0.05), horizontalalignment='right', verticalalignment='top') ax.set (xlim= (- 1,5), ylim= (- 3,5))

Draw the image as follows:

two。 Draw a 3D image

3D images need to be imported into the Axes3D library.

From mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as pltfrom matplotlib import cmfrom matplotlib.ticker import LinearLocator, FormatStrFormatterimport numpy as npfig = plt.figure (figsize= (15Power15)) ax = fig.gca (projection='3d') # Make data.X = np.arange (- 5,5,0.25) Y = np.arange (- 5,5,0.25) X, Y = np.meshgrid (X, Y) R = np.sqrt (X, Y) Z = np.sin (R) # Plot the surface.surf = ax.plot_surface (X Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis.ax.set_zlim (- 1.01,1.01) ax.zaxis.set_major_locator (LinearLocator (10)) ax.zaxis.set_major_formatter (FormatStrFormatter ('.02f')) # Add a colorbar which maps values to colors.fig.colorbar (surf, shrink=0.5, aspect=5)

Cmap means colormap, which is used to draw color distribution, gradient, and so on. Cmap is usually used with colorbar to draw the color bar of an image.

3. Import image (California house price)

Introduce the mpimg library to import images.

We take the California house price data as an example, import the California house price data to draw the scatter chart, and import the California map picture to view the longitude and latitude corresponding to the house price data. At the same time, use the color bar to draw a heat image.

The code is as follows:

Import osimport urllibimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.image as mpimg# California house price data (never mind the domain name) housing = pd.read_csv ("http://blog.caiyongji.com/assets/housing.csv")# map of California url =" http://blog.caiyongji.com/assets/california.png"urllib.request.urlretrieve("http://blog.caiyongji.com/assets/california.png", os.path.join (". /") "california.png")) california_img=mpimg.imread (os.path.join (". /", "california.png")) # draw house price scatter chart according to longitude and latitude ax = housing.plot (kind= "scatter", x = "longitude", y = "latitude", figsize= (10L7), s=housing ['population'] / 100, label= "Population", c = "median_house_value", cmap=plt.get_cmap ("jet") Colorbar=False, alpha=0.4,) plt.imshow (california_img, extent= [- 124.55,-113.80, 32.45,42.05], alpha=0.5, cmap=plt.get_cmap ("jet") plt.ylabel ("Latitude", fontsize=14) plt.xlabel ("Longitude", fontsize=14) prices = housing ["median_house_value"] tick_values = np.linspace (prices.min (), prices.max () 11) # Color bar Heat map cbar = plt.colorbar (ticks=tick_values/prices.max ()) cbar.ax.set_yticklabels (["$% dk"% (round (Vmax 1000)) for v in tick_values], fontsize=14) cbar.set_label ('Median House Value', fontsize=16) vplt.legend (fontsize=16)

Draw the image as follows:

Red is expensive, blue is cheap, and the size of the circle indicates the population.

4. Draw contours

Contours are useful for drawing 3D images in 2D space.

Def f (x, y): return np.sin (x) * * 10 + np.cos (10 + y * x) * np.cos (x) x = np.linspace (0,5,50) y = np.linspace (0,5,40) X, Y = np.meshgrid (x, y) Z = f (X, Y) plt.contourf (X, Y, Z, 20, cmap='RdGy') plt.colorbar ()

Draw the image as follows:

The black place is the peak and the red place is the valley.

Draw animation

Drawing animation requires the introduction of animation library, by calling the FuncAnimation method to achieve drawing animation.

Import numpy as npfrom matplotlib import pyplot as pltfrom matplotlib import animationfig = plt.figure () ax = plt.axes (xlim= (0,2), ylim= (- 2,2)) line, = ax.plot ([], [], lw=2) # initialization method def init (): line.set_data ([], []) return line,# data update method Periodically call def animate (I): X = np.linspace (0,2, 1000) y = np.sin (2 * np.pi * (x-1000 * I)) line.set_data (x, y) return line,# to draw animation, number of frames frames The interval periodic line calls the animate method anim = animation.FuncAnimation (fig, animate, init_func=init, frames=200, interval=20, blit=True) anim.save ('ccccc.gif', fps=30) plt.show ()

The anim.save () method in the above code supports saving files in mp4 format.

The dynamic picture is drawn as follows:

These are all the contents of the article "what are the common uses of Matplotlib?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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

Internet Technology

Wechat

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

12
Report