1、饼状图
#使用pie()绘制饼状图
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #转换汉字
labels = ["A部门","B部门","C部门","D部门"] #各部分标签
nums = [0.25,0.15,0.36,0.24] #占比数
colors = ["#377eb8","#4daf4a","#984ea3","#ff7f00"] #四种颜色
explode = (0.1,0.1,0.1,0.1)
plt.pie(nums,explode=explode,labels=labels,autopct="%3.1f%%",\
startangle=45,shadow=True,colors=colors)
plt.title("一季度各部门盈利构成") #标题
plt.show() #输出饼状图
结果:
2、柱状图
import matplotlib.pyplot as plt #下载matplotlib包
import numpy as np #下载numpy包
x = np.arange(1,13)
y = [6.2,4.9,5.3,4.7,8.3,9.2,15.3,14.2,21.7,19.6,5.7,5.1] #每一年的数据
y1 = [2.6,1.2,3.4,6.5,8.9,13.5,25.9,28.2,32.7,25.9,15.3,3.7]
bar_width = 0.4 #柱子的宽度
tick_label = ["1M","2M","3M","4M","5M","6M",\
"7M","8M","9M","10M","11M","12M",] #月份
plt.bar(x,y,align="center",color="r",width=bar_width,label="2019Money",alpha=0.5) #第一个柱子的值
plt.bar(x+bar_width,y1,align="center",color="g",width=bar_width,label="2020Money",alpha=0.5)#第二个柱子的值
plt.xticks(x+bar_width/2,tick_label)
plt.legend()
plt.show()
结果