# Python visual Matplotlib -- Chapter 2: detailed explanation of all usage of Matplotlib line graph plot()

Matplotlib The column contains this content
3 articles 2 subscription

Line graph is a very common graph in data analysis. Among them, the broken line chart is mainly a statistical chart showing the increase or decrease of the statistical quantity by the rise or fall of the broken line. It is used to analyze the trend relationship between independent variables and dependent variables. It is most suitable for displaying continuous data that changes over time. At the same time, it can also see the difference and growth of quantity.

• Features: it can display the change trend of data and reflect the change of things.

The function of drawing line chart in Matplotlib is plot (), and the syntax is as follows:

matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)


Common parameters and Description:

x，yarrayRepresents the data corresponding to the x-axis and y-axisnothing
colorstringRepresents the color of the polylineNone
markerstringRepresents the type at the data point on the polylineNone
linestylestringIndicates the type of polyline-
linewidthnumerical valueLine thickness: linewidth = 1. = 5. = 0.3one
alphaDecimals between 0 and 1Represents the transparency of pointsNone
labelstringData legend content: label = "actual data"1None

# 1. Improve the original line chart - add auxiliary functions to the graph

Demand: draw a broken line diagram of temperature change per minute in an hour from 11:00 to 12:00 in a city, with the temperature range of 15 degrees to 25 degrees

## 1.1 prepare the data and draw the initial line chart

importmatplotlib.pyplot asplt
importrandom

#Draw the temperature change diagram

#0. Prepare the data of X and Y coordinates
x = range(sixty)
y_ jiangsu = [random.uniform(fifteen, twenty-five) fori inx]

#1. Create canvas
plt.figure(figsize=(twenty, eight),dpi=eighty)

#2. Draw line chart
plt.plot(x,y_jiangsu)

#3. Display image
plt.show()


## 1.2 add custom x, y scale

• plt.xticks(x, **kwargs)

x: Scale value to display

• plt.yticks(y, **kwargs)

y: Scale value to display

#Construct X-axis scale labels
x_ ticks_ label = ["11:00 {}".format(i) fori inx]
#Construct Y-axis scale
y_ ticks = range(forty)

#Modify the scale display of X and Y axis coordinates
plt.xticks(x[::five],x_ticks_label[::five])
plt.yticks(y_ticks[::five])


## 1.3 Chinese display problem solving

If the Chinese problem has not been solved, the drawn image will be unable to be displayed in Chinese.

Solution 2:
Dynamically set matplotlibrc in Python script to avoid the trouble caused by changing the configuration file. The specific code is as follows:

from pylab import mpl
#Set display Chinese font
mpl.rcParams["font.sans-serif"] = ["SimHei"]


Sometimes, after the font is changed, some characters in the coordinate axis cannot be displayed normally, for example, the negative sign cannot be displayed. At this time, axes.unicode needs to be changed_ Minus parameter:

#Set normal display symbol
mpl.rcParams["axes.unicode_minus"] = False


In order to more clearly observe the corresponding values of the graph

plt.grid(True, linestyle='--', alpha=0.5)


Add x-axis, Y-axis description information and title

The size of the font in the image can be modified through the fontsize parameter

Plt.xlabel ("time")
Plt.ylabel ("temperature")
PLT. Title ("temperature change diagram between 11:00 and 12:00 noon in Jiangsu", fontsize = 20)


## 1.6 image saving

#Save the picture to the specified path
plt.savefig("test.png")


Note: PLT. Show() will release the figure resource. If you save a picture after displaying an image, you can only save an empty picture.

# 2. Draw multiple images in one coordinate system

## 2.1 multiple plot

Demand: add another city's temperature change
The temperature changes of the day in Beijing were collected, and the temperature ranged from 1 ℃ to 3 ℃. How to add another different figure in the same coordinate system is actually very simple. You only need to plot again, but you need to distinguish lines.

#Add temperature data of Beijing
y_ beijing = [random.uniform(1, 3) for i in x]

#Draw a line chart
plt.plot(x, y_jiangsu)
#Multiple polylines can be drawn using multiple plots
plt.plot(x, y_beijing, color='r', linestyle='--')


## 2.2 display legend

• Note: if you can't finally display the legend by only setting label in plot. Plot(), you need to display the legend through plot. Legend().
#Draw a line chart
Plot.plot (x, y_jiangsu, label = "Jiangsu")
#Multiple polylines can be drawn using multiple plots
Plot.plot (x, y_beijing, color ='r ', linestyle =' -- ', label = "Beijing")

#Display legend
plt.legend(loc="best")


Full code:

#0. Prepare data
x = range(sixty)
y_ jiangsu = [random.uniform(fifteen, twenty-five) fori inx]
y_ beijing = [random.uniform(one,three) fori inx]

#1. Create canvas
plt.figure(figsize=(twenty, eight),dpi=one hundred)

#2. Draw image
plt.plot(x,y_jiangsu,label="Jiangsu")
plt.plot(x,y_beijing,color="r",linestyle="--",label="Beijing")

#2.1 add x, Y axis scale
#Construct x, Y axis scale labels
x_ ticks_ label = ["11:00 {}".format(i) fori inx]
y_ ticks = range(thirty-five)

#Scale display
plt.xticks(x[::five],x_ticks_label[::five])
plt.yticks(y_ticks[::five])

plt.grid(True,linestyle="--",alpha=zero point five)

plt.xlabel("Time")
plt.ylabel("Temperature")
plt.title("Temperature change map of a city from 11:00 to 12:00",fontsize=twenty)

#2.4 image saving
plt.savefig("./test.png")

plt.legend(loc="best")

#3. Image display
plt.show()


## 2.3 application scenario of line chart

• Show the number of active users per day of the company's products (different regions)
• After the new functions of the product are launched, the number of user clicks changes with time

Creation is not easy, white whoring is not good. Your support and recognition is the biggest driving force for my creation. See you in the next article!

Dragon youth

If there are any mistakes in this blog, please comment and advice. Thank you very much!

• two
give the thumbs-up
• 0
comment
• three
Collection
• Sweep and share posters

Insert expression
Can also inputone thousandCharacters
©️ 2020 CSDN Skin theme: swimming - white Designer: Bai Songlin
Paid inelement
Payment with balance
Click retrieve
Code scanning payment
Wallet balance 0

Deduction Description:

1. The balance is the virtual currency of wallet recharge, and the payment amount is deducted according to the ratio of 1:1.
2. The balance cannot be purchased and downloaded directly. You can buy VIP, c-coin package, paid column and courses.

Balance recharge