数学建模程序部分之绘图可视化 计划实现语言:python¶
参考https://zhuanlan.zhihu.com/p/347717545¶
https://matplotlib.org/stable/gallery/index.html¶
In [6]:
import matplotlib.pyplot as plt #调用pyplot,以这个包为基础应该能满足数学建模基础作图要求
x = [1, 2, 3, 4, 5]
y = [2.3, 3.4, 1.2, 6.6, 7.0]
plt.scatter(x, y, color='r', marker='+')#这里颜色和线型都可以调整,我们可以提前确定一下作图风格
Out[6]:
In [8]:
# https://www.runoob.com/w3cnote/matplotlib-tutorial.html
#这里有非常详尽的基本图像调节指南↑
import numpy as np#numpy不是绘图的库嗷,是以矩阵为基础的数学计算模块,在数据处理的时候非常常见
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)#这里在规定范围,从− −π到 π线性分割出256份
C,S = np.cos(X), np.sin(X)
C = C + np.random.rand(256)*0.2#这里是加了个随机噪声,稍微复杂一下图像案例
S = S + np.random.rand(256)*0.4
plt.rcParams['figure.dpi'] = 100 #好像是设置点间密度用的
plt.plot(X,C)
plt.plot(X,S)
# 以分辨率 72 来保存图片
# savefig("exercice_2.png",dpi=72)
plt.show()
#如果想要更改线型颜色,也ok
# help(plt.plot)
# 提示:使用help(plt.plot)以查看帮助文档,这非常有用
plt.plot(X,C, 'gs--', linewidth=0.8,markersize=2)
plt.plot(X,S,color="red",marker="1", linewidth=0.4, linestyle="-")
plt.show()
关于以上实例的进一步说明¶
我们还可以在他的基础上改变坐标轴大小和画布的尺寸,
调整坐标的分度值,
移动坐标轴在画面中的位置,
调整透明度,
增加图例,
标注特别的点
作为提纲指南,此处不一一展示,需要时见以上两个网址即可
进阶使用¶
在matplotlib中还有海量图示可以使用,我尝试通读一遍example,并扒出我认为可能用到的(或者只是花里胡哨的)进一步说明。
按惯例,需要时借鉴https://matplotlib.org/stable/gallery/index.html 官网案例即可。
Lines, bars and markers¶
来几个柱形图
In [25]:
N = 5
menMeans = (20, 35, 30, 35, -27)
womenMeans = (25, 32, 34, 20, -25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots()
p1 = ax.bar(ind, menMeans, width, yerr=menStd, label='Men')
p2 = ax.bar(ind, womenMeans, width,
bottom=menMeans, yerr=womenStd, label='Women')
ax.axhline(0, color='grey', linewidth=0.8)
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend()
# Label with label_type 'center' instead of the default 'edge'
#ax.bar_label(p1, label_type='center')#!!!!!这里出现问题导致数字显示不出来
#ax.bar_label(p2, label_type='center')
#ax.bar_label(p2)
plt.show()
In [24]:
#制作一组数据的直方图
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
x = np.arange(len(labels)) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabe