Matplotlib简介
Matplotlib 是一个 Python 的 2D绘图库。通过 Matplotlib,开发者 可以仅需要几行代码,便可以生成绘图,直方图,功率谱,条形 图,错误图,散点图等。
置中文标题
Matplotlib 默认情况不支持中文,我们可以使用以下简单的方法来 解决:
plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签
折线图
from matplotlib import pyplot as plt
#准备数据
max_temperature = [26, 30, 20, 32, 25]
min_temperature = [12, 16, 16, 28, 20]
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
#生成x
x =range(5)
#xticks(x,x_ticks)
x_ticks = [f'星期{i}' for i in range(1,6)]
plt.xticks(x,x_ticks)
#给y轴添加名称
plt.ylabel('温度:单位(℃)')
#添加标题
plt.title('某年某月第N周的温度')
plt.plot(x,max_temperature,label='最高温度')
plt.plot(x,min_temperature,label='最低温度')
#添加图例
# plt.legend(loc=4)
plt.legend(loc='upper right')
直方图
# 获取数据
data = [45, 49, 42, 42, 36, 37, 31, 38, 35,
39, 43, 33, 34, 36, 35, 36, 34, 32, 36, 32,
37, 33, 32, 38, 35]
# 设置组距
bin_width = 2
# 设置分组
bin_count = int((max(data) - min(data)) /
bin_width)
# 设置x轴标签位置
x = range(bin_count)
x_ticks = range(31, 50, 2)
# 设置x轴标签的值
plt.xticks(x_ticks)
# 填充数据
plt.hist(data, bin_count)
饼图
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
#准备男、女的人数及比例
man=71351
woman=68187
#计算男生女生所占的比
man_perc = man /(man+woman)
woman_perc = woman /(man+woman)
labels = ['男','女']
# colors = ['blue','red']
#调用pie绘制饼图 传入一个列表,列表中是比例数据
paches,texts,autotexts = plt.pie([man_perc,woman_perc],
autopct='%0.1f%%',
labels=labels,
explode =(0,0.1)
)
#设置字体大小和颜色
for text in autotexts:
text.set_color('white')
text.set_fontsize(24)
for t in texts:
t.set_color('white')
t.set_fontsize(24)
散点图
import matplotlib.pyplot as plt
import numpy as np
# 绘制不同大小不同颜色的散点图
np.random.seed(0)
x=np.random.rand(100)
y=np.random.rand(100)
colors=np.random.rand(100)
size=np.random.rand(100)*1000
plt.scatter(x,y,c=colors,s=size,alpha=0.7)
plt.show()
箱线图
from matplotlib import pyplot as plt
import numpy as np
#准备数据
data = [np.random.normal(0,i,100) for i in range(1,4)]
#调用 boxplot()
#vert:是竖着还是横着
#notch:切口 更好找到中位数
plt.boxplot(data,vert=True,notch=True)
plt.title('boxplot')
plt.xticks([1,2,3],['box1','box2','box3'])
三维图
from matplotlib import pyplot as plt
import numpy as np
#准备数据
x = np.linspace(-10,10,100)
y = np.linspace(-10,10,100)
#计算x y 的相交点
X,Y = np.meshgrid(x,y)
#计算Z
Z = np.sqrt(X**2+Y**2)
#绘制三维图
# plt.contour(X,Y,Z)
plt.contourf(X,Y,Z)
#三维画布绘制三维图
from mpl_toolkits.mplot3d import Axes3D
figure = plt.figure()
ax3d = Axes3D(figure)
ax3d.plot_surface(X,Y,Z)
条形图
from matplotlib import pyplot as plt
import numpy as np
#准备数据
x = range(3)
x_label = ['bar1','bar2','bar3']
y = [1,2,3]
#波动
variance= [0.2,0.4,0.5]
#绘制柱形图
plt.bar(x,y,width=0.5,yerr=variance)
plt.xticks(x,x_label)
#设置y轴坐标的范围
m = max(zip(y,variance))
maxy = (m[0]+m[1])*1.2
plt.ylim([0,maxy])
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)