欢迎光临散文网 会员登陆 & 注册

第十章 第三方库-Matplotlib-2

2023-07-13 09:41 作者:wangyanhpa  | 我要投稿

10.1.1条形图

垂直条形图

import matplotlib.pyplot as plt

 

def autolabel(rects):

  for rect in rects:

    height = rect.get_height()

    plt.text(rect.get_x() + rect.get_width() / 2, 1.02 * height, "%s" % int(height))

 

# 这两行代码解决 plt 中文显示的问题

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

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

colors=['red','yellowgreen']

number = [26, 17]

widths = [0.2, 0.2]

plt.xlabel("性别")

plt.ylabel("人数")

 

plt.xticks((0,1),("男","女"))

 

plt.title('选课学生性别比例图')

rect = plt.bar(range(2), number,width = widths,color=colors,align="center",yerr=0.000001)

autolabel(rect)

plt.show()

 

水平条形图

import matplotlib.pyplot as plt

import numpy as np

# 这两行代码解决 plt 中文显示的问题

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

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

 

fig,ax = plt.subplots()

majors = ('计算机','石工','外语','经管','地质')

numbers = [3,6,2,7,9]

y_pos = np.arange(len(majors))

# range 和 arange 的作用是类似的,只不过arange 可以接受非int 类型的数据

# np.arange(len(people)) 的结果就是[0,1,2,3,4]

 

rects = ax.barh(y_pos,numbers,color='greenyellow',align="center")

ax.set_yticks(y_pos) # 设置标度的位置

ax.set_yticklabels(majors) # 设置纵坐标的每一个刻度的属性值

 

ax.invert_yaxis()  # 反转标度值,不起作用

plt.title('选课学生专业分布图')

ax.set_xlabel('选课人数') # 设置横坐标的单位

ax.set_ylabel('专业') # 设置纵坐标的单位

# show the number in the top of the bar

for rect,y,num in zip(rects,y_pos,numbers):

    x= rect.get_width()

    plt.text(x+0.05,y,"%d" % int(num))

 

plt.show()

10.1.2折线图

import numpy as np

import matplotlib.pyplot as plt

cc= np.linspace(0,2,100) #创建等差数列(0,2)分成100份

plt.rcParams['font.sans-serif'] = ['SimHei']#设置字体为SimHei显示中文

plt.plot(cc,cc,label='linear') #(x,x)坐标画图

plt.plot(cc,cc**2,label='两倍')#(x,x平方)坐标画图

plt.plot(cc,cc**3,label='三倍')#(x,x三次方)坐标画图

plt.xlabel('x label')#x坐标轴名

plt.ylabel('y label')#y坐标轴名

plt.title("折线图")#图名

plt.legend()#给加上图例

plt.show()#显示图像

10.1.3散点图

import numpy as np

import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.2) #起点0,终点5,步长0.2

plt.plot(x, x, 'r--', x, x**2, 'bs', x, x**3, 'g^')

#红色--(x, x),蓝色方块(x, x**2),绿色三角(x, x**3)

plt.show()

10.1.4饼图

import matplotlib.pyplot as plt

 

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

labels = '男生', '女生'

sizes = [33,  45]

explode = (0,  0)

colors = ['red','yellowgreen']

patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors,

labeldistance = 1.1,autopct = '%3.1f%%',shadow = False,

startangle = 90,pctdistance = 0.6)

for t in l_text:

  t.set_size(20)

for t in p_text:

  t.set_size(20)

 

plt.axis('square')

plt.show()

import matplotlib.pyplot as plt

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

labels = '大一', '大二', '大三', '大四'

sizes = [15, 30, 45, 10]

explode = (0, 0, 0.1, 0)

plt.pie(sizes, explode=explode, labels=labels,

        autopct='%1.1f%%',shadow=False, startangle=0)

plt.axis('square')

plt.show()


第十章 第三方库-Matplotlib-2的评论 (共 条)

分享到微博请遵守国家法律