本文记录matpltlib库中主要的绘图命令,列出各类型绘图的简单案例。
图形 | 函数 |
---|---|
曲线图 | .plot(data) |
灰度图 | .hist(data) |
散点图 | .scatter(data) |
箱式图 | .boxplot(data) |
直方图 | .bar(data) |
饼状图 | .pie(data) |
热图 | .imshow(data) |
等高线图 | .contourf(data) |
雷达图 | p.olar(data) |
查看函数可用参数的方法
import matplotlib.pyplot as plt
help(plt.plot)
import numpy as np
import matplotlib.pyplot as plt
#申请一块画布
fig=plt.figure(figsize=(20,15))
#画三张图
ax1=fig.add_subplot(4,3,1)
ax2=fig.add_subplot(4,3,2)
ax3=fig.add_subplot(4,3,3)
ax4=fig.add_subplot(4,3,4)
ax5=fig.add_subplot(4,3,5)
ax6=fig.add_subplot(4,3,6)
ax7=fig.add_subplot(4,3,7)
ax8=fig.add_subplot(4,3,8)
ax9=fig.add_subplot(4,3,9)
ax10=fig.add_subplot(4,3,10)
ax11=fig.add_subplot(4,3,11,projection='polar')
ax12=fig.add_subplot(4,3,12)
#折线图
ax1.plot(np.random.randn(10))
#曲线图
x2=np.arange(-10,10,0.1)
y2=x2**2
ax2.plot(x2,y2)
#灰度图
ax3.hist(np.random.normal(size=1000),bins=100,alpha=0.3)
#散点图
ax4.scatter(np.random.normal(size=1000),2*np.random.normal(size=1000))
#直方图
ax5.bar(np.arange(10),np.random.randn(10))
#直方图
ax6.barh(np.arange(10),np.random.randn(10))
#饼状图
ax7.pie(np.random.randint(1,15,5),explode=[0.05,0.25,0.20,0.30,0.20])
#热图
import pandas as pd
from pandas import Series,DataFrame
df=DataFrame(np.random.randn(10,10))
ax8.imshow(df.values,interpolation='nearest')
#多图种混合
x9=np.arange(10)
y9=np.random.randn(10)
ax9.plot(x9,y9,color='red')
ax9.bar(x9,y9,color='green')
#等高线图
x10=np.linspace(-3,3,256)
y10=np.linspace(-3,3,256)
x10,y10=np.meshgrid(x10,y10)
z10=(1-x10/2+x10**5+y10**3)*np.exp(-x10**2-y10**2)
ax10.contourf(x10,y10,z10,8,alpha=.75,cmap=plt.cm.cool)
#雷达图
attribute=['Attack','Defence','Stamina','Agility','Magicka']
theta=np.linspace(0,2*np.pi,len(attribute),endpoint=False)
value=np.random.randint(50,100,size=5)
theta = np.concatenate((theta,[theta[0]]))
value = np.concatenate((value,[value[0]]))
#ax11=polar(theta,value,lw=2)
#箱体图
x12=np.random.randn(10,10)
ax12=plt.boxplot(x12)
#3D曲面图
from mpl_toolkits.mplot3d import Axes3D
x21=np.arange(-2,2,0.1)
y21=np.arange(-2,2,0.1)
x21,y21=np.meshgrid(x21,y21)
bx1=plt.figure()
pk1=Axes3D(bx1)
pk1.plot_surface(x21,y21,(1-y21**5+x21**5)*np.exp(-x21**2-y21**2), rstride=1, cstride=1, color='red', alpha=.4)
#3D散点图
x22=np.random.randint(30,40,100)
y22=np.random.randint(20,25,100)
z22=np.random.randint(0,5,100)
x23=np.random.randint(55,60,100)
y23=np.random.randint(10,20,100)
z23=np.random.randint(35,40,100)
bx2=plt.figure()
pk2=Axes3D(bx2)
pk2.scatter(x22,y22,z22,c='r',marker='^',zdir='z')
pk2.scatter(x23,y23,z23,c='g',marker='*',zdir='z')
·函数格式
plt.plot(x,y,format_string,**kwargs)
x,y - 分别为自变量和因变量
Format_string – 绘图格式,如点型,线型,颜色(参数见附录1)
**kwargs – 绘制多条曲线;设置 label / linewidth等参数
·属性设置
用样式 | 函数 |
---|---|
标题 | pyplot.title() |
坐标轴标签 | pyplot.xlabel() |
图注 | pyplot.legend() |
网格 | pyplot.grid() |
字符 | .rcParams() |
绘图区域 | pyplot.subplot2grid() |
import matplotlib.pyplot as plt
import numpy as np
#设置变量和自变量
x=np.arange(-5,5,0.2)
y1=x**2/20
y2=np.exp(-1-x**2)
y3=np.cos(x/np.pi)
y4=np.sin(x/np.pi)
#绘制曲线
plt.figure()
plt.subplot2grid((2,2),(0,0),colspan=2)
plt.plot(x,y1,color='green', marker='*', linestyle='--', linewidth=1, markersize=6,label='y1')
plt.plot(x,y2,color='blue',marker='+',linestyle='-',label='y2')
plt.plot(x,y3,'ro',linestyle=':',label='y3')
#设置pyplot属性
plt.ylabel('Y value')
plt.title('Example of plot')
plt.legend(loc='best')
#另设两个小区域
plt.subplot2grid((2,2),(1,0))
x2=(3,5,7,9)
y5=(6,11,8,7)
plt.plot(x2,y5)
plt.subplot2grid((2,2),(1,1))
plt.plot(x,y3,'ro',linestyle=':',label='y3')
plt.show()
hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, *, data=None, **kwargs)
常用参数:
x
:输入值,需要为一个序列。唯一必选参数
bins
:区间数量,可以指定为整数或者列出全部区间。
range
:配合bins,只在range制定范围内划分bins区间
desity
:默认输出为频数直方图,将density设为True后变为频率直方图
stack
:是否允许堆叠。stack=True 则允许数据堆叠
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
plt.subplot2grid((2,2),(0,0))
data=np.random.normal(size=1000)
plt.hist(data)
#分为30个区间
plt.subplot2grid((2,2),(0,1))
plt.hist(data,30)
#仅在(-2,2)区分30个区间
plt.subplot2grid((2,2),(1,0))
plt.hist(data,30,(-2,2))
#改为频率直方图
plt.subplot2grid((2,2),(1,1))
plt.hist(data,30,(-2,2),density=True)
plt.show()
```python
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(15,10))
#多组数据放到一个直方图里,并列排布
plt.subplot2grid((2,2),(0,0))
data1=np.random.randint(0,5000,5000)
data2=500*np.random.normal(0,1,3000) +2250
data3=1000*np.random.normal(0,1,3000) +2250
labels = ['randint','normal-1','normal-2']
bins = [0, 500,1000, 1500,2000,2500,3000,3500,4000,4500,5000]
plt.hist([data1,data2,data3],bins=bins,label=labels,color=['r','g','b'])
plt.legend()
#多组数据放到一个直方图里,重叠排布
plt.subplot2grid((2,2),(0,1))
data4=500*np.random.normal(0,1,8000) +2250
plt.hist(data2,color='r',alpha=1,label='nomal-1')
plt.hist(data4,color='g',alpha=0.2,label='nomal-3')
plt.legend()
#多组数据放到一个直方图里,堆叠排布
plt.subplot2grid((2,2),(1,0))
data5=np.random.randn(10000)
data6=np.random.randn(10000) +2.5
data7=np.random.randn(10000) -1
plt.hist([data5,data6,data7],bins=100,stacked=True,density=True,label=['randn-1','randn-2','randn-3'])
plt.legend()
scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, *, plotnonfinite=False, data=None, **kwargs)
常用参数:
x,y
:输入值,需要为一个序列。必选参数
s,c,marker
:大小,颜色,点的标识
alpha
:透明度
linewidth,edgecolors
:边的宽度及颜色
cmap
:点颜色渐变
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(10,20,2)
y=x**(0.5)+20/x
plt.figure()
#基本图形
plt.subplot2grid((2,2),(0,0))
plt.scatter(x,y)
#增加颜色等
plt.subplot2grid((2,2),(0,1))
plt.scatter(x,y,s=1000,c="r",marker="d")
#增加边
plt.subplot2grid((2,2),(1,0))
plt.scatter(x,y,s=1000,c="r",marker="d",linewidth=3,edgecolors="b")
#渐变
plt.subplot2grid((2,2),(1,1))
plt.scatter(x,y,c=y,cmap=plt.cm.Reds)
plt.show()
boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_ticks=True, autorange=False, zorder=None, *, data=None)
常用参数:
X
:输入值。唯一必选参数。
Notch
:是否是凹口形式
patch_artist
:箱线颜色是否填充
medianprops
:中位数线的属性
boxprops
:箱体的属性
meanprops
:均值的属性
whiskerprops
:猫须属性
capprops
:箱线图顶末端线条属性
sym
:异常点形状
import matplotlib.pyplot as plt
import numpy as np
data1=np.random.normal(0,1,10)
data2=np.random.normal(0,1,100)
data3=np.random.normal(0,1,1000)
plt.boxplot([data1, data2,data3], labels = ['10 sample','100 sample','1000 sample'])
import matplotlib.pyplot as plt
import numpy as np
data1=np.random.normal(0,1,10)
data2=np.random.normal(0,1,100)
data3=np.random.normal(0,1,1000)
plt.boxplot([data1, data2,data3], labels = ['10 sample','100 sample','1000 sample'],vert=False,showmeans=True,notch = True,sym = '*',patch_artist = True, boxprops = {
'color':'orangered','facecolor':'pink'})
bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
常用参数:
x
:输入值。必选参数。
height
:输入值。必选参数。
width
: 柱状图宽度(0~1)
import matplotlib.pyplot as plt
import numpy as np
X = np.arange(8)+1
Y1 = np.random.uniform(0.5,1.0,8)
Y2 = np.random.uniform(0.3,1.0,8)
plt.bar(X, Y1, alpha=0.9, width = 0.35, facecolor = 'lightskyblue', edgecolor = 'white', label='one', linewidth =1)
plt.bar(X+0.35, Y2, alpha=0.9, width = 0.35, facecolor = 'yellowgreen', edgecolor = 'white', label='second', linewidth =1)
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(10,4))
x = np.arange(10)
y1 = np.random.rand(10)
y2 = -np.random.rand(10)
#正负柱状图
plt.bar(x,y1,width = 1,facecolor = 'yellowgreen',edgecolor = 'white',yerr = y1*0.1)
plt.bar(x,y2,width = 1,facecolor = 'lightskyblue',edgecolor = 'white',yerr = y2*0.1)
#增加标注
for i,j in zip(x,y1):
plt.text(i-0.15,j-0.15,'%.2f' % j, color = 'white')
for i,j in zip(x,y2):
plt.text(i-0.15,j+0.05,'%.2f' % -j, color = 'white')
pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, *, data=None)
常用参数:
x
:输入值。必选参数。
explode
:各饼之间间距
colors
:各饼的填充色
autopct
:百分比显示格式
pctdistance
:百分比标签与圆心距离
labeldistance
:图例标签与圆心距离
startangle
:初始摆放角度
radius
:饼图半径
center
:中心点位置
from matplotlib import pyplot as plt
plt.figure(figsize=(6,9))
labels = ['part 1','part 2','part 3']
sizes = [40,30,20]
colors = ['red','yellowgreen','lightskyblue']
textprops={
'fontsize':18,'color':'black'}
plt.pie(sizes,explode=explode,labels=labels,colors=colors,labeldistance = 1.1,autopct = '%3.1f%%',shadow = False,startangle = 90,pctdistance = 0.6,textprops=textprops)
plt.axis('equal')
plt.legend()
plt.show()
from matplotlib import pyplot as plt
plt.figure(figsize=(6,9))
#设定各pie标识
labels = ['part 1','part 2','part 3','part 4']
#设定各pie颜色
colors = ['red','yellowgreen','lightskyblue','hotpink']
#设定标注字体
textprops={
'fontsize':12,'color':'black'}
#设定圆盘线宽
wedgeprops={
'linewidth':1,'edgecolor':'black'}
#绘制外圈
sizes_1 = [40,30,20,10]
plt.pie(sizes_1,radius=1.0,labels=labels,colors=colors,labeldistance = 1.1,autopct = '%3.1f%%',shadow = False,startangle = 90,pctdistance = 0.85,textprops=textprops,wedgeprops=wedgeprops)
#绘制中圈,覆盖部分外圈
sizes_2 = [35,30,15,20]
plt.pie(sizes_2,radius=0.7,colors=colors,autopct = '%3.1f%%',shadow = False,startangle = 90,pctdistance = 0.75,textprops=textprops,wedgeprops=wedgeprops)
#绘制内圈,白色覆盖
sizes_3 = [1]
plt.pie(sizes_3, radius=0.4,colors = 'w',wedgeprops=wedgeprops)
plt.axis('equal')
plt.legend()
plt.show()
imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=<deprecated parameter>, filternorm=1, filterrad=4.0, imlim=<deprecated parameter>, resample=None, url=None, *, data=None, **kwargs)
x
:输入值。必选参数。
cmap
:颜色图谱
interpolation
:模糊度设置。
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(20,12))
x=np.random.randn(10,10)
syscmap=['autumn','bone','cool','copper','flag','gray','hot','hsv','inferno','jet','magma','pink','plasma','prism','spring','summer','viridis','winter']
for i in range(3):
for j in range(6):
plt.subplot2grid((3,6),(i,j))
plt.imshow(x,cmap=syscmap[6*i+j])
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(20,12))
sysinterpolation=['none','none','nearest','bilinear','bicubic','spline16','spline36','hanning','hamming','hermite','kaiser','quadric','catrom','gaussian','bessel','mitchell','sinc','lanczos']
for i in range(3):
for j in range(6):
plt.subplot2grid((3,6),(i,j))
plt.imshow(x,cmap='hot',interpolation=sysinterpolation[6*i+j])
可用的Colors, Markers, Linestyles,这些内容可用help() 命令中看到。
Colors
The following color abbreviations are supported:
============= ===============================
character color
============= ===============================
``'b'`` blue
``'g'`` green
``'r'`` red
``'c'`` cyan
``'m'`` magenta
``'y'`` yellow
``'k'`` black
``'w'`` white
============= ==============================
**Markers**
============= ===============================
character description
============= ===============================
``'.'`` point marker
``','`` pixel marker
``'o'`` circle marker
``'v'`` triangle_down marker
``'^'`` triangle_up marker
``'<'`` triangle_left marker
``'>'`` triangle_right marker
``'1'`` tri_down marker
``'2'`` tri_up marker
``'3'`` tri_left marker
``'4'`` tri_right marker
``'s'`` square marker
``'p'`` pentagon marker
``'*'`` star marker
``'h'`` hexagon1 marker
``'H'`` hexagon2 marker
``'+'`` plus marker
``'x'`` x marker
``'D'`` diamond marker
``'d'`` thin_diamond marker
``'|'`` vline marker
``'_'`` hline marker
============= ==============================
**Line Styles**
============= ===============================
character description
============= ===============================
``'-'`` solid line style
``'--'`` dashed line style
``'-.'`` dash-dot line style
``':'`` dotted line style
============= ===============================
Example format strings::
'b' # blue markers with default shape
'ro' # red circles
'g-' # green solid line
'--' # dashed line with default color
'k^:' # black triangle_up markers connected by a dotted line