python使用matplotlib 绘制各种图表
散点图
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(10)
y = np.random.rand(10)
plt.scatter(x, y)
plt.show()
柱状图
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
x = [1,2,3,4,5,6,7,8]
y = [3,1,4,5,8,9,7,2]
label=['A','B','C','D','E','F','G','H']
plt.bar(x,y,tick_label = label)
plt.show()
折线图
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
x = [1,2,3,4,5,6,7,8]
y = [3,1,4,5,8,9,7,2]
plt.plot(x, y)
plt.show()
饼图
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
x = ['A','B','C','D','E','F','G','H','I','J','K']
y = [60605,54546,45819,28243,13270,9945,7679,6799,6101,4621,20105]
plt.pie(y, labels=x, autopct="%1.2f%%")
plt.show()
圆环图
import matplotlib.pyplot as plt
x = [1, 5, 4, 3]
labels = ['a', 'b', 'c', 'd']
plt.subplot(122)
plt.pie(x, labels=labels)
plt.show()
气泡图
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = [1125, 1725, 2250, 2875, 2900, 3750, 4125]
y = [6, 8, 10, 13, 14, 16, 21]
z = [25, 40, 58, 68, 110, 98, 120]
colors = np.random.rand(len(y))
size = x
plt.scatter(y, z, s=size, c=colors, alpha=0.6)
plt.show()
相关图
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
data = np.array([[1,2,6],[4,5,6],[7,8,9]])
sns.heatmap(data,annot=True)
plt.show()
雷达图
import matplotlib.pyplot as plt
import numpy as np
theta = np.array([0.25,0.75,1,1.5,0.25])
r = [20,60,40,80,20]
plt.polar(theta*np.pi,r,"r-",lw=1)
plt.fill(theta*np.pi,r,'r',alpha=0.75)
plt.ylim(0,100)
#显示网格线
plt.grid(True)
plt.show()
箱型图
import numpy as np
import matplotlib.pyplot as plt
from pandas import DataFrame
df = DataFrame({'Parameter': ['A',]*8,
'Site': ['S1', 'S2', 'S1', 'S2', 'S1', 'S2', 'S1', 'S2'],
'Value': [2.34, 2.67, 2.56, 2.89, 3.45, 4.45, 3.67, 4.56]})
df.boxplot(by=['Parameter', 'Site'])
plt.show()
树形图
import matplotlib.pyplot as plt
import squarify
name = ['国内增值税','国内消费税','企业所得税','个人所得税',
'进口增值税、消费税','出口退税','城市维护建设税',
'车辆购置税','印花税','资源税','土地和房税','车船税烟叶税等']
income = [3908,856,801,868,1361,1042,320,291,175,111,414,63]
colors = ['steelblue','#9999ff','red','indianred',
'green','yellow','orange']
plot=squarify.plot(
sizes=income,#指定绘图数据
label=name,#标签
color=colors,#指定自定义颜色
alpha=0.6,#指定透明度
value=income,#添加数值标签
)
plt.axis('off')
plt.show()
堆叠折线图
import matplotlib.pyplot as plt
date =[1,2,3,4,5]
earn=[156,356,574,300,687]
pay=[[15,30,27,43,21],[22,38,27,18,42]]
plt.stackplot(date,earn,pay, colors=['green','yellow','orange'])
plt.show()
堆叠柱状图
import matplotlib.pyplot as plt
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
width = 0.35 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots(figsize=(5,3),dpi=200)
ax.bar(labels, men_means, width,label='Men')
ax.bar(labels, women_means, width, bottom=men_means,label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.legend()
plt.show()
3D曲面图
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
ax.contourf(X,Y,Z,zdir='z',offset=-2)
ax.set_zlim(-2,2)
plt.show()
3D散点图
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
x = np.arange(0, 200)
y = np.arange(0, 100)
x, y = np.meshgrid(x, y)
z = np.random.randint(0, 200, size=(100, 200))
y3 = np.arctan2(x,y)
ax.scatter(x, y, z, c=y3, marker='.', s=50, label='')
plt.show()
3D柱状图
import random
import matplotlib as mpl
import matplotlib.dates as mdates
from mpl_toolkits.mplot3d import Axes3D
mpl.rcParams['font.size'] = 10
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for z in [2011, 2012, 2013, 2014]:
xs = range(1,13)
ys = 1000 * np.random.rand(12)
color = plt.cm.Set2(random.choice(range(plt.cm.Set2.N)))
ax.bar(xs, ys, zs=z, zdir='y', color=color, alpha=0.8)
ax.xaxis.set_major_locator(mpl.ticker.FixedLocator(xs))
ax.yaxis.set_major_locator(mpl.ticker.FixedLocator(ys))
ax.set_xlabel('Month')
ax.set_ylabel('Year')
ax.set_zlabel('Sales Net [usd]')
plt.show()
子图
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
%matplotlib inline
fig, axes = plt.subplots(2,3,figsize=(20,10)) #这个可以方便同时建立画板画布
axes[0,1].plot(np.random.randn(10)) #第1行第二个画布绘图
axes[0,2].plot(np.random.randn(10),'g--',marker='o')
arr = np.random.randn(20).cumsum()
axes[1,1].plot(data,linestyle='--',color='red',marker='o')
plt.plot(data,'k--') #未给定画布则在最后一个画布上绘图
axes[1,0].plot(arr,linestyle='dashed',color='yellow',marker='*')
data = DataFrame(np.random.randn(2,3),columns=['a','b','c'])
data.plot(ax=axes[0,0]) #针对DataFrame可以使用参数给定画布
plt.show()