Python data analysis --- matplotlib line chart basic practice combat

Install matplotlib

pip install matplotlib #Installation using the command line is best to use the domestic mirror source, of
course, you can also install in pycharm

Basic usage

figure Two parameters: figsize (), a tuple in parentheses, set the size of the graph. dpi is sharpness
plot Drawing, if you draw multiple lines, then plot multiple times. You can specify the color, for example color = 'r'
savefig Save the picture, savefig ("./ t1.png")
xlabel Two parameters, the first is the description information of the x-axis, the second is to set the Chinese
ylabel Two parameters, the first is the description of the y-axis, the second is to set the Chinese
title Table title
xticks x-axis scale
yticks Y-axis scale
show Graphic display method
legend Add legend, prop to set Chinese, and loc legend placement. At the same time add label in the plot () method

Code display

Assuming that when you are 30 years old, according to the actual situation, the number of girlfriends you and your tablemates from 11 to 30 years old each year are listed, such as list a and list b. Draw a line chart of the data in a graph.
a = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
b = [2,3, 0,5,3,4,2,4,6,7,3,5,2,7,1,1,1,1,1,1]

from matplotlib import pyplot as plt
from matplotlib import font_manager
#交女朋友的数量看作y轴
y_1 = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
y_2 = [2,3,0,5,3,4,2,4,6,7,3,5,2,7,1,1,1,1,1,1]
#设置x是从11岁到30岁
x = range(11,31)
#设置中文,由于我的其中一项中文字体单独放在了E盘
my_font = font_manager.FontProperties(fname="E:\msyh.ttc")
#设置图形大小
plt.figure(figsize=(15,8),dpi=80)
#两个折线图放一张表,所以两次plot
plt.plot(x,y_1,label="自己",color="r")
plt.plot(x,y_2,label="同桌",color='g')
#设置x轴刻度,使x轴出现多少岁
_xtick_labels = ["{}岁".format(i) for i in x]
plt.xticks(x,_xtick_labels,fontproperties=my_font)
#绘制网格,并设置透明度,网格线格式是点
plt.grid(alpha=0.4,linestyle=':')
#添加描述信息
plt.xlabel("年龄",fontproperties=my_font)
plt.ylabel("女朋友的数量",fontproperties=my_font)
plt.title("统计交往的异性",fontproperties=my_font)

#添加图例,并中文显示
plt.legend(prop=my_font)
#展示
plt.show()

running result

Insert picture description here

Published 26 original articles · praised 5 · visits 777

Guess you like

Origin blog.csdn.net/weixin_44730235/article/details/104651450