Matplotlib学习笔记3
程序员文章站
2022-03-19 23:38:09
...
1、盒形图绘制:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
tang_data = [np.random.normal(0,std,100) for std in range(1,4)]
fig = plt.figure(figsize = (8,6)) #区域大小
plt.boxplot(tang_data,notch=False,sym='s',vert=True)
#notch=False基本形状,sym=‘s’方块,vert=True竖着画
plt.xticks([y+1 for y in range(len(tang_data))],['x1','x2','x3'])
plt.xlabel('x')
plt.title('box plot')
更改盒形图颜色:
for components in bplot.keys():
for line in bplot[components]:
line.set_color('black')
也可以横着画,只需要vert=False:
tang_data = [np.random.normal(0,std,100) for std in range(1,4)]
fig = plt.figure(figsize = (8,6))
plt.boxplot(tang_data,notch=False,sym='s',vert=False)
plt.yticks([y+1 for y in range(len(tang_data))],['x1','x2','x3'])
plt.ylabel('x')
plt.title('box plot')
当然你要实在闲着没事干,甚至可以把盒子形状改一下,notch=True。
或者更改一下盒子的颜色:
tang_data = [np.random.normal(0,std,100) for std in range(1,4)]
fig = plt.figure(figsize = (8,6))
bplot = plt.boxplot(tang_data,notch=False,sym='s',vert=True,patch_artist=True)
#patch_artist=True才可以填充颜色
plt.xticks([y+1 for y in range(len(tang_data))],['x1','x2','x3'])
plt.xlabel('x')
plt.title('box plot')
colors = ['pink','lightblue','lightgreen']
for pathch,color in zip(bplot['boxes'],colors):
pathch.set_facecolor(color)
2、小提琴图:violinplot
fig,axes = plt.subplots(nrows=1,ncols=2,figsize=(12,5))
tang_data = [np.random.normal(0,std,100) for std in range(6,10)]
axes[0].violinplot(tang_data,showmeans=False,showmedians=True)
axes[0].set_title('violin plot')
axes[1].boxplot(tang_data)
axes[1].set_title('box plot')
for ax in axes:
ax.yaxis.grid(True)
ax.set_xticks([y+1 for y in range(len(tang_data))])
plt.setp(axes,xticks=[y+1 for y in range(len(tang_data))],xticklabels=['x1','x2','x3','x4'])
3、对于轴的操作:
x = range(10)
y = range(10)
fig = plt.gca() #对轴操作
plt.plot(x,y)
fig.axes.get_xaxis().set_visible(False) #消去轴的刻度
fig.axes.get_yaxis().set_visible(False)
4、去掉上右两轴且带网格的直方图:
import math
x = np.random.normal(loc = 0.0,scale=1.0,size=300)
width = 0.5
bins = np.arange(math.floor(x.min())-width,math.ceil(x.max())+width,width)
ax = plt.subplot(111)
ax.spines['top'].set_visible(False) #去除上轴
ax.spines['right'].set_visible(False) #去除右轴
plt.tick_params(bottom='off',top='off',left = 'off',right='off') #消除轴上的指示线
plt.grid() #加上网格
plt.hist(x,alpha = 0.5,bins = bins) #hist直方图
5、轴标签:
x = range(10)
y = range(10)
labels = ['godx' for i in range(10)]
fig,ax = plt.subplots()
plt.plot(x,y)
plt.title('godx')
ax.set_xticklabels(labels,rotation = 45,horizontalalignment='right')
#rotation = 45倾斜角,horizontalalignment='right'右对齐
import matplotlib as mpl
mpl.rcParams['axes.titlesize'] = '10' #更改图标题的大小
6、一个图多条曲线+图例:
x = np.arange(10)
for i in range(1,4):
plt.plot(x,i*x**2,label = 'Group %d'%i)
plt.legend(loc='best') #在图里加上图例,loc='best'放在最好的位置
也可指定其他位置upper center、lower left等
ax.legend(loc='upper center',bbox_to_anchor = (0.5,1.15) ,ncol=3)
#把图例放在图外面,上方,(0.5,1.15)表示位置,nocl=3表示横着写(3列)
ax.legend(loc='upper center',bbox_to_anchor = (1.15,1) ,ncol=1)
#ncol=1竖着写(1列)
plt.legend(loc='upper right',framealpha = 0.1) #将图例设置为透明
7、直方图:
最简单的:
data = np.random.normal(0,20,1000)
bins = np.arange(-100,100,5)
plt.hist(data,bins=bins)
plt.xlim([min(data)-5,max(data)+5])
plt.show()
两个变量的直方图:
import random
data1 = [random.gauss(15,10) for i in range(500)]
data2 = [random.gauss(5,5) for i in range(500)]
bins = np.arange(-50,50,2.5)
plt.hist(data1,bins=bins,label='class 1',alpha = 0.3) #设置alpha可以看两组数据堆叠程度
plt.hist(data2,bins=bins,label='class 2',alpha = 0.3)
plt.legend(loc='best') #图例
plt.show()
8、散点图的绘制:
mu_vec1 = np.array([0,0])
cov_mat1 = np.array([[2,0],[0,2]]) #协方差矩阵
x1_samples = np.random.multivariate_normal(mu_vec1, cov_mat1, 100)
x2_samples = np.random.multivariate_normal(mu_vec1+0.2, cov_mat1+0.2, 100)
x3_samples = np.random.multivariate_normal(mu_vec1+0.4, cov_mat1+0.4, 100)
plt.figure(figsize = (8,6))
plt.scatter(x1_samples[:,0],x1_samples[:,1],marker ='x',color='blue',alpha=0.6,label='x1')
plt.scatter(x2_samples[:,0],x2_samples[:,1],marker ='o',color='red',alpha=0.6,label='x2')
plt.scatter(x3_samples[:,0],x3_samples[:,1],marker ='^',color='green',alpha=0.6,label='x3')
plt.legend(loc='best')
plt.show()
也可以在散点图中加入每个点的坐标:
x_coords = [0.13, 0.22, 0.39, 0.59, 0.68, 0.74, 0.93]
y_coords = [0.75, 0.34, 0.44, 0.52, 0.80, 0.25, 0.55]
plt.figure(figsize = (8,6))
plt.scatter(x_coords,y_coords,marker='s',s=50) #s=50点的大小
for x,y in zip(x_coords,y_coords):
plt.annotate('(%s,%s)'%(x,y),xy=(x,y),xytext=(0,-15),textcoords = 'offset points',ha='center')
#加注释,textcoords = 'offset points'加坐标,ha='center'对齐
plt.show()
离某个点越远点越大:
mu_vec1 = np.array([0,0])
cov_mat1 = np.array([[1,0],[0,1]])
X = np.random.multivariate_normal(mu_vec1, cov_mat1, 500)
fig = plt.figure(figsize=(8,6))
R=X**2
R_sum=R.sum(axis = 1)
plt.scatter(X[:,0],X[:,1],color='grey',marker='o',s=20*R_sum,alpha=0.5)
plt.show()