python3数学建模基础(一)绘制各类型的图表
本文适合有python3的numpy库和matplotlib库基础的读者。
你需要:①Python IDLE 3.x
②在python中安装numpy库和matplotlib库,推荐pip方法安装
接下来我会在源代码中展示柱状图,折线图,饼图的几个有趣的示例。
系列文章
- python3数学建模基础(一)绘制各类型的图表
- python3数学建模基础(二)矩阵运算
- python3数学建模基础(三)实现斐波那契数列
- python3数学建模基础(四)多个函数图像求交点
- python3数学建模基础(五)矩阵乘法和按位乘法
- python3数学建模基础(六)字符串选择性条件拼接
- python3数学建模基础(七)函数曲线方程的方法控制输出位置
源代码:
#作者
#生姜用户
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(7) #x产生7组
#y1,y2 = np.random.randint(1,49,size=(2,7)) #y1,y2随机产生,7*7=49
y1=[5,5,5,5,5,5,5]
y2=[1,2,3,4,5,6,7]
width = 0.25 #代表柱状图的宽度
ax = plt.subplot(1,1,1)
ax.bar(x,y1,width,color='blue',label='y1') #bar 是绘制柱状图
ax.bar(x+width,y2,width,color='red',label='y3') #设置x轴,y轴,宽度,颜色
ax.set_xticks(x+.5*width) #一半的柱宽正好可以让字母处于中间
ax.set_xticklabels(['a','b','c','d','e','f','g']) #自定义x的刻度标签的内容
plt.plot(x,y1) #这两行又在原有基础上连了一个折线图
plt.plot(x,y2)
plt.legend(loc=0)
plt.ylabel('LY1')
plt.xlabel('LX1')
plt.title('title is just here')
#以下为饼图
label=['A','B','C','D']
size=[12,30,45,10] #数字为饼的分块占比
fig,ax=plt.subplots() #面向对象画图
explode=(0,0.2,0,0) #第二块扇形移出,数值越大,移除的距离越远
plt.title('title2 is just here')
ax.pie(size,labels=label,autopct='%1.1f%%',shadow=True,startangle=45,explode=explode) #autopct自动显示百分比 shadow=90显示出阴影 startangle=90饼图倾斜与正
ax.axis('equal') #将椭圆变为圆
plt.show()
这两张图就是上述程序的运行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/a9d3802a1ac36a163fbed134ea8e7f75.png)
![](https://i-blog.csdnimg.cn/blog_migrate/846c1e94da945a4af114a64237daaeff.png)