Python--Matplotlib——学习

原文链接

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(431)
ax2 = fig.add_subplot(432)
ax3 = fig.add_subplot(433)
ax4 = fig.add_subplot(434)
ax5 = fig.add_subplot(435)
ax6 = fig.add_subplot(436)
ax7 = fig.add_subplot(437)
ax8 = fig.add_subplot(438)
ax9 = fig.add_subplot(439)


"""1、线"""
x = np.linspace(0,np.pi)
y_sin = np.sin(x)
y_cos = np.cos(x)

ax1.plot(x,y_cos,color='red',linewidth=2,markersize=12,marker='+',linestyle='dashed')
ax1.set(title='line')

"""2、点"""
x2=np.arange(10)
x2=np.random.randn(10)
ax2.scatter(x2,x2,color='red',edgecolor='yellow',marker='*')
ax2.set(title='points')


"""3、条状图"""
np.random.seed(1) #每次运行代码时设置相同的seed,则每次生成的随机数也相同,如果不设置seed,则每次生成的随机数都会不一样。
x3=np.arange(5)
y3=np.random.randn(5)  #随机数、正态分布
vert_bars=ax3.bar(x3,y3,color='lightblue',align='center')
horiz_bars=ax4.barh(x3,y3,color='lightblue',align='center')

for bar, height in zip(vert_bars, y3):
    if height < 0:
        bar.set(edgecolor='darkred', color='red', linewidth=3)
for bar, height in zip(horiz_bars, y3):
    if height < 0:
        bar.set(edgecolor='darkred', color='red', linewidth=3)
ax3.axhline(0,color='grey',linewidth=2)
ax3.set(title='vert')
ax4.axvline(0,color='grey',linewidth=2)
ax4.set(title='horiz')


"""4、直方图"""
np.random.seed(19680801)
n_bins=10
x4=np.random.randn(100,3)

colors=['red','tan','lime']
#参数中density控制Y轴是概率还是数量,与返回的第一个的变量对应。
# histtype控制着直方图的样式,默认是 ‘bar’,即ax5;‘barstacked’ 就是叠在一起,即ax6
ax5.hist(x4,n_bins,density=True,histtype='bar',color=colors,label=colors)
ax5.legend(prop={'size':10})
ax5.set(title='bars with legend')

ax6.hist(x4,n_bins,density=True,histtype='barstacked',color=colors,label=colors)
ax6.legend(prop={'size':10})
ax6.set(title='stacked bar')

ax7.hist(x4,histtype='barstacked',rwidth=0.9) #rwidth 控制着宽度,这样可以空出一些间隙


"""5、饼图"""
labels='A','B','C','D'
sizes=[15,30,45,10]
explode = (0,0,0.1,0) ## 偏移,突出

ax8.pie(sizes,labels=labels,autopct='%1.1f%%',shadow=True)
ax8.axis('equal')
#autopct=%1.1f%%表示格式化百分比精确输出,explode,突出某些块,不同的值突出的效果不一样。pctdistance=1.12百分比距离圆心的距离,默认是0.6.
#从90度开始画图,标签,逆时针
ax9.pie(sizes,labels=labels,autopct='%1.1f%%',shadow=False,startangle=90,explode=explode,pctdistance=1.12)
ax9.axis('equal')


"""6、箱形图"""
ax1.boxplot(data)
ax2.boxplot(data2,vert=False) #控制反向


"""7、泡泡图"""
np.random.seed(19680801)

N = 50
x7 = np.random.rand(N)
y7 = np.random.rand(N)
colors = np.random.rand(N)
area = 5*(30 * np.random.rand(N)**2)
ax1.scatter(x7,y7,s=area,c=colors)


"""8.等高线"""
x8 = np.arange(-5,5,0.1)
y8 = np.arange(-5,5,0.1)
xx,yy = np.meshgrid(x8,y8,sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
ax3.contourf(x8,y8,z)
ax4.contour(x8,y8,z)

plt.show()

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值