【Python】Matplotlib库基础绘图函数(子绘图,饼图、直方图、玫瑰图、散点图、条形图)

内容来源

中国大学MOOC 《Python数据分析与展示(嵩天)》第二周 单元4、单元5

推荐大家直接去看视频

子绘图

1、plt.subplot2grid()

#pyplot 子绘图区域
import numpy as py
import matplotlib.pyplot as plt

plt.subplot2grid((3,3),(0,0),colspan=3)
plt.subplot2grid((3,3),(1,0),colspan=2)
plt.subplot2grid((3,3),(1,2),rowspan=2)
plt.subplot2grid((3,3),(2,0))
plt.subplot2grid((3,3),(2,1))

【Python】Matplotlib库基础绘图函数(子绘图,饼图、直方图、玫瑰图、散点图、条形图)_第1张图片

2、gridspec.GridSpec()

import matplotlib.gridspec as gridspec

gs =  gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:-1])
ax3 = plt.subplot(gs[1:,-1])
ax4 = plt.subplot(gs[2,0])
ax5 = plt.subplot(gs[2,1])

【Python】Matplotlib库基础绘图函数(子绘图,饼图、直方图、玫瑰图、散点图、条形图)_第2张图片

两个代码画的图其实是一样的:图片一个是窗口模式,一个是内置模式罢了

饼图、直方图、玫瑰图、散点图、条形图

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

gs =  gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:-1])
ax3 = plt.subplot(gs[1:,-1])
ax4 = plt.subplot(gs[2,0])
ax5 = plt.subplot(gs[2,1])
###################################################################
#1 plt.pie() 饼图
labels = 'Frogs','Hogs','Dogs','Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)
#plt.pie(sizes,explode=explode)
ax4.pie(sizes,explode=explode, labels=labels,autopct='%1.1f%%',
        shadow=False,startangle=90)
plt.axis('equal')  
plt.show()

#2 plt.hist() 直方图
np.random.seed(0)
mu, sigma =100, 20  #mean std
a = np.random.normal(mu, sigma, size=100)
#plt.hist(a, 20, normed=1, histtype='stepfilled', facecolor='r', alpha=0.75)#bin 直方的个数  alpha为透明度
ax2.hist(a, 40, normed=1, histtype='stepfilled', facecolor='r', alpha=0.65)
ax2.set_title('Histogram')
plt.show()

#3 plt.polar()  极坐标 南丁格尔玫瑰图
N = 20
theta = np.linspace(0.0, 2*np.pi, N, endpoint=False)
radii = 10*np.random.rand(N)
width = np.pi/4*np.random.rand(N)
ax = plt.subplot(gs[2,1],projection='polar')  #ax5 = plt.subplot(gs[2,1])
bars = ax.bar(theta, radii, width=width, bottom=0.0)
for r,bar in zip(radii, bars):
    bar.set_facecolor(plt.cm.viridis(r/10.))
    bar.set_alpha(0.5)
plt.show()
'''
theta = np.linspace(0.0, 2*np.pi, N, endpoint=False)
radii = 10*np.random.rand(N)
plt.polar(theta, radii, color="chartreuse", linewidth=2, marker="*", mfc="b", ms=10)
'''

#4 plt.scatter散点图
ax =  plt.subplot(gs[1:,-1])
ax.plot(10*np.random.randn(100),10*np.random.randn(100),'o')
ax.set_title('Simple Scatter')

plt.show()

#plt.bar(left,height,width,bottom)
ax1.bar(np.arange(20),np.random.rand(20),width=0.8,color='g')
plt.show()


【Python】Matplotlib库基础绘图函数(子绘图,饼图、直方图、玫瑰图、散点图、条形图)_第3张图片

你可能感兴趣的:(Python)