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 the matplotlib Library of python to draw

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to use python matplotlib library drawing", the explanation content in the article is simple and clear, easy to learn and understand, please follow the idea of Xiaobian slowly in-depth, together to study and learn "how to use python matplotlib library drawing"!

I. Foreword

Python's matplotlib library is powerful enough to draw all kinds of images. First, install some basic libraries, such as numpy,matplotlib, or pandas.

II. Basic Orders

First, introduce the basic commands commonly used when drawing:

1.plt.plot(x,y) is the drawing command.① Basic drawing:

plt.plot(x, y)

② Set color:

The color attribute can be set manually without special requirements. If you want to draw different lines on a picture, it will automatically assign colors. You can also use ax.plot for the same effect.

plt.plot(x, y, color = 'red')

③ Set line type:

The lineStyle property can be selected from '-','-','-. ', ':', ' None',', ' solid','dashed',' dashdot','dotted', these types.

plt.plot(x, y, lineStyle = 'dashdot')

④ Set the label type:

The marker attribute has different marker choices, such as 'o','*',' x'.

④ Set legend:

label attribute.

plt.plot(x, y ,marker ='o ',label ='Chinese Score') plt.plot(x, y ,marker ='*',label ='Math Score') plt.plot(x, y ,marker ='x ',label ='English Score')

Only such legend will not be displayed, but also need to add loc is the position setting, see the details explained later.

plt.legend(loc='upper left') III. Normal display Chinese:

The Windows system:

plt.rcParams['font.family'] = ['sans-serif']plt.rcParams['font.sans-serif'] = ['SimHei']

Mac system: here is the setting, can also be set to other Chinese fonts.

plt.rcParams["font.family"] = 'Arial Unicode MS'

② Normal display symbol:

plt.rcParams ['axes.unicode_minus'] = False

① If you only draw one picture, you can. Figsize is the ratio of the size of the picture in the x axis and y axis directions. Here to be set well, otherwise there may be incomplete picture display situation, if saved through the savefig command, but also according to this proportion to save the picture.

f = plt.figure(figsize=(8,6))

Or, although it is through the subplots command, but do not specify nrows and ncols default to only one subplot.

f, ax = plt.subplots(figsize=(8,6))

ax represents the current coordinate axis.

ax = plt.gca()

If there are multiple subimages: nrows for rows, ncols for columns, figsize for the size of the image.

f, ax = plt.subplots(nrows=2,ncols=1,figsize=(8,6),facecolor='white')

or

fig = plt.figure()ax1 = fig.add_subplot(2,1,1)ax2 = fig.add_subplot(2,1,2)ax1.plot(x,y)ax2.plot(x,z)

or

ax1 = plt.subplot(2,1,1)ax2 = plt.subplot(2,1,2)ax1.plot(x,y)ax2.plot(x,z)

Other attributes: The first attribute tag is the name of the window and the resolution of the dpi setting.

f = plt.figure ('results window', figsize=(8,6),facecolor='white', dpi=100)

② Set the background color of the picture:

f = plt.figure(figsize=(8,6),facecolor='blue')

If you want to set the foreground color of the picture, use

ax.set(facecolor='white')

V. Set x-axis or y-axis related attributes:

① Set the scale of x axis: you need to specify the position of the label, the specific value of the label, and you can specify the size through fontsize.

x = [0,2,4,6,8]x_label = ['Semester 1',' Semester 2','Semester 3',' Semester 4','Semester 5'] plt.xticks(x, x_label,fontsize=13)

xticks here support latex,

x_label = [r'$e^x,r'$x_1^2,r'$lambda,r'$frac{1}{2},r'$pi]

Sometimes there may be a lot of labels, and we want to display the scale on the x axis vertically: just add a 'newline' to the x_label where you want to newline.

x = [0,2,4,6,8]x_label = ['1st Semester','2nd Semester','3rd Semester','4th Semester','5th Semester']plt.xticks(x, x_label,fontsize=13)#Here's a picture

② Set the label of x axis: These two commands have the same effect.

plt.xlabel(u"term")ax.set_xlabel(u"term")#Set label value for x axis

xlabel also supports latex

plt.xlabel(u"$x^2$")

③ Set the range of x axis: These two commands have the same effect. Generally do not need to manually specify the range, the program will automatically determine a range based on the input maximum and minimum values.

plt.xlim(0,100)ax.set_xlim(0,100)

The y-axis attributes are set in the same way as the x-axis attributes. You just need to replace x with y.

VI. Set title:

fontsize is the size, fontweight specifies bold. The following two commands have the same effect.

plt.title ('Line Chart of Changes in Xiao Ming's Grade from the First to the Fourth Semester ',fontsize=18,fontweight=' bold') ax.set_title ('Line Chart of Changes in Xiao Ming's Grade from the First to the Fourth Semester ',fontsize=18,fontweight=' bold')

Here the program will automatically put the title in a suitable position, of course, it is inevitable that the title is not the position we want, which can be set by specifying the x or y attribute. The normal range is [0,1]. You can set negative zero or one point. You need to try more. If you set it beyond the range of the picture, you will not see the title. For example, here I set y=-0.1, you can see that the title goes below.

plt.title ('Line Chart of Changes in Xiao Ming's Grade from the First to the Fourth Semester ',fontsize=18,fontweight=' bold', y=-0.1)

VII. Setting Legend:

Method 1: Make a good mark when drawing.

plt.plot(x, y[0,:],marker ='o ',label ='Chinese Score') plt.plot(x, y[1,:],marker ='*',label ='Math Score') plt.plot(x, y[2,:],marker ='x ',label ='English Score') plt.legend(loc ='upper left')

Law 2: Do not write in plot, uniformly write in legend. You can specify the corresponding curve. The curve definition here must be followed by ',' or an error will be reported.

a,=plt.plot(x, y[0,:],marker ='o ')b,=plt.plot(x, y[1,:],marker ='*')c,=plt.plot(x, y[2,:],marker ='x ')plt.legend((a,b,c),('Chinese performance',' Math performance','English performance'),loc ='upper left')

Or you don't specify a corresponding curve,

plt.legend(('Chinese Score','Math',' English Score'),loc='upper left')

It is not recommended to specify the corresponding curve. Sometimes it is not desirable to add legend to each curve. For curves without legend, the label attribute can not be written. This method will add legends in the order of plot, and will not skip curves that do not want to add legends, unless it is the last curve, which will not be added without writing. Legend command can only be set by plt, if there are multiple subgraphs,

ax = plt.subplot(2,1,1)

This allows plt operations to be performed on subgraphs.

VIII. Marking:

If you want to label, you need to write a loop, label one by one, you can't write plt.text(x,y,"%s"%str(y)) like this, you won't label a bunch at a time. fontsize is the font that sets the label. Ax is the same.

for i in range(len(x)): plt.text(x[i],y[i],"%s"%str(y[i]), fontsize=12) #ax.text(x[i],y[i],"%s"%str(y[i]), fontsize=12)

Legend often blocks the image content. You can also specify the position of legend here.

Legend's position can be adjusted via the bbox_to_anchor attribute.

plt.legend(bbox_to_anchor=(1.05, 1), loc=2)

Legends have many other attributes,

IX. Save picture: plt.savefig ('Xiaoming grade change picture.png') X. Display picture: plt.show() XI. Delete border:

There are four directions, and you can choose which direction to remove the border.

ax.spines ('right ').set_visible(False)ax.spines ('top').set_visible(False)ax.spines ('bottom ').set_visible(False)ax.spines ('left').set_visible(False) XII. Display/Not Display Grid: ax.grid(True)ax.grid(False) Thank you for reading, the above is "how to use python matplotlib library drawing" content, after learning this article, I believe that everyone on how to use python matplotlib library drawing this problem has a deeper understanding, the specific use of the situation also needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

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

Development

Wechat

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

12
Report