Quick start with matplotlib.pyplot


1. What is plt?

Matplotlib is a plotting library for Python that allows users to easily visualize data and provide a variety of output formats. Pyplot is a sub-library of Matplotlib that provides a drawing API similar to MATLAB.
Reference link 1
Reference link 2
import matplotlib.pyplot as plt

2. Use steps

1. Drawing a single line chart

x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
y_beijing = [random.uniform(1,3) for i in x]
plt.figure(figsize=(20,8),dpi=160) 						# 创建画布,figsize和dpi可以不写
plt.plot(x,y_shanghai,color="r",linestyle="--",label="ShangHai") 	# color : r g b c m y k
plt.plot(x,y_beijing,color="b",linestyle=":",label="BejJing") 		# linestyle : - -- -. :
plt.legend(loc=0) 										# loc="best"/"upper right"... 0/1/...
plt.xticks(range(0,60,2)) 								# 传入要显示的刻度值
plt.yticks(range(0,38,2))
plt.grid(linestyle="--",alpha=0.5)
plt.xlabel("time")
plt.ylabel("temperature")
plt.title("test image")
plt.savefig("./test.jpg") 								# 保存图片,要在show图片之前
plt.show() 												# 会释放figure资源,如果在显示图像之后保存图片将只保存空白图片

2. Multiple graph drawing

# 多个绘图区,使用面向对象的方式
figure,axes = plt.subplots(nrows=1,ncols=2,figsize=(20,8),dpi=180) # 返回画布和绘图区
axes[0].plot(x,y_shanghai,color="r",linestyle="--",label="ShangHai")
axes[1].plot(x,y_beijing,color="b",linestyle=":",label="BejJing")
axes[0].legend(loc=0)
axes[1].legend(loc=0)
axes[0].set_xticks(range(0,60,2))
axes[0].set_yticks(range(0,38,2))
axes[1].set_xticks(range(0,60,2))
axes[1].set_yticks(range(0,38,2))
axes[0].grid()
axes[1].grid()
axes[0].set_xlabel("time")
axes[0].set_ylabel("temperature")
axes[0].set_title("test image BeiJing")
axes[1].set_xlabel("time")
axes[1].set_ylabel("temperature")
axes[1].set_title("test image ShangHai")
plt.show()

3.

plt.scatter(x,y) 				 		# 散点图
plt.bar(x,y)							# 柱状图
plt.hist(y,bins=20,density=True) 		# 直方图,bins设置组数,density设置是否将频数展示为频率
--------------------------------------------------------------------------------------------------------------
plt.pie(x,labels=y,autopct="%.2f%%")	# 饼图
plt.axis("equal") 						# 让x和y轴相等

Summarize

For example: the above is what I will talk about today. This article only briefly introduces the use of matplotlib.pyplot

Guess you like

Origin blog.csdn.net/goodlmoney/article/details/126799793