Python数据分析之matplotlib(提高篇)

时间:2022-07-22
本文章向大家介绍Python数据分析之matplotlib(提高篇),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

散点图(scatter)

fig,axes = plt.subplots(ncols=2,nrows=2)
ax1,ax2,ax3,ax4 = axes.ravel()
# example1
height=[161,170,182,175,173,165]
weight=[50,58,80,70,69,55]
ax1.scatter(height,weight) #绘制横坐标为身高,纵坐标为体重散点图

# example2
N = 1000
x = np.random.randn(N) #随机生成一千个点
y = np.random.randn(N) #随机生成一千个点
ax2.scatter(x,y) #绘制横坐标为x,纵坐标为y散点图

# example3

open,close=np.loadtxt('000001.csv',delimiter=',',skiprows=1,usecols=(1,4),unpack=True)
# loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
# fname:读取文件的文件名。例如 '000001.csv'。
# dtype:数据类型。如float,str等。默认为float
# comments 注释
# delimiter:数据之间的分隔符。如使用逗号','。默认是空格
# skiprows跳过前几行读取,默认是0,必须是int整型。
# usecols:选取数据的列。
# unpack如果为True,将分列读取。

change=close-open
yesterday=change[:-1]
today=change[1:]
ax3.scatter(today,yesterday)

# example4
ax4.scatter(today,yesterday,s=50,c='r',marker='<',alpha=0.5)
# s:尺寸大小
# c: 颜色类型
# marker: 标记形状
plt.show()

条形图 (bar)

fig,axes = plt.subplots(ncols=2,nrows=2)
ax1,ax2,ax3,ax4 = axes.ravel()

N=5

y=[20,10,30,25,15]

index = np.arange(N)
# bar绘制条形图
ax1.bar(left=index, height=y,width=0.3) #left:横坐标值 height:纵坐标值 width:条形图宽度
ax2.bar(left=index, height=y,color='red',width=0.3) # color:设置条形图颜色
ax3.bar(left=0, bottom=index, width=y,height=0.5,orientation='horizontal')# orientation:'horizontal'设置为横向
ax4.barh(bottom=index,width=y,height=0.5) # barh 横向条形图
plt.show()
fig,axes = plt.subplots(ncols=2,nrows=2)
ax1,ax2,ax3,ax4 = axes.ravel()

index=np.arange(4)

sales_BJ=[52,55,63,53]
sales_SH=[44,66,55,41]
bar_width=0.3

ax1.bar(index,sales_BJ,bar_width,color='b')
ax1.bar(index+bar_width,sales_SH,bar_width,color='r') # index+bar_width实现横向并排

ax2.bar(index,sales_BJ,bar_width,color='b')
ax2.bar(index,sales_SH,bar_width,color='r',bottom=sales_BJ) # bottom=sales_BJ实现纵向叠加

ax3.barh(bottom=index,width=sales_BJ,height=0.3,color='b')
ax3.barh(bottom=index+bar_width,width=sales_SH,height=0.3,color='r') # bottom=index+bar_width

ax4.barh(bottom=index,width=sales_BJ,height=0.3,color='b')
ax4.barh(bottom=index,width=sales_SH,height=0.3,color='r',left=sales_BJ) # left=sales_BJ

plt.show()

直方图(hist)

fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(212)

mu = 100
sigma = 20
x = mu +sigma * np.random.randn(2000)

ax1.hist(x,bins=10,color='green',normed=True) #输入数据,bins=总共有几条条状图,color=颜色,normed=True:纵坐标总共为1

ax2.hist(x,bins=50,color='red',normed=False) #normed=False:纵坐标显示实际值


x = np.random.randn(1000)+2
y = np.random.randn(1000)+3

ax3.hist2d(x,y,bins=10) #二维直方图

plt.show()

饼状图(pie)

labels='frogs','hogs','dogs','logs'
sizes=15,20,45,10
colors='yellowgreen','gold','lightskyblue','lightcoral'
explode=0,0.1,0,0
plt.pie(sizes,explode=explode,labels=labels,colors=colors,labeldistance = 1.1 ,autopct='%3.1f%%',shadow=True,startangle=90,pctdistance = 0.6)
#labeldistance,文本的位置离远点有多远,1.1指1.1倍半径的位置
#autopct,圆里面的文本格式,%3.1f%%表示小数有三位,整数有一位的浮点数
#shadow,饼是否有阴影
#startangle,起始角度,0,表示从0开始逆时针转,为第一块。一般选择从90度开始比较好看
#pctdistance,百分比的text离圆心的距离
plt.axis('equal') #修正为正圆 设置x,y轴刻度一致,这样饼图才能是圆的
plt.show()

箱型图(boxplot)

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

np.random.seed(100)

data = np.random.normal(size=1000, loc=0.0, scale=1.0)

ax1.boxplot(data,sym='o',whis=1.5)
# plt.boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=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)
# x:指定要绘制箱线图的数据;
# notch:是否是凹口的形式展现箱线图,默认非凹口;
# sym:指定异常点的形状,默认为+号显示;
# vert:是否需要将箱线图垂直摆放,默认垂直摆放;
# whis:指定上下须与上下四分位的距离,默认为1.5倍的四分位差;
# positions:指定箱线图的位置,默认为[0,1,2…];
# widths:指定箱线图的宽度,默认为0.5;
# patch_artist:是否填充箱体的颜色;
# meanline:是否用线的形式表示均值,默认用点来表示;
# showmeans:是否显示均值,默认不显示;
# showcaps:是否显示箱线图顶端和末端的两条线,默认显示;
# showbox:是否显示箱线图的箱体,默认显示;
# showfliers:是否显示异常值,默认显示;
# boxprops:设置箱体的属性,如边框色,填充色等;
# labels:为箱线图添加标签,类似于图例的作用;
# filerprops:设置异常值的属性,如异常点的形状、大小、填充色等;
# medianprops:设置中位数的属性,如线的类型、粗细等;
# meanprops:设置均值的属性,如点的大小、颜色等;
# capprops:设置箱线图顶端和末端线条的属性,如颜色、粗细等;
# whiskerprops:设置须的属性,如颜色、粗细、线的类型等;
data = np.random.normal(size=(100, 4), loc=0.0, scale=1.0)

labels = ['A','B','C','D']

ax2.boxplot(data, labels=labels)

plt.show()

颜色与样式

颜色

样式

  • 线条样式
  • 标记样式
fig = plt.figure()
ax1 = fig.add_subplot(321)
ax2 = fig.add_subplot(322)
ax3 = fig.add_subplot(323)
ax4 = fig.add_subplot(324)
ax5 = fig.add_subplot(313)

#内建默认颜色
y=np.arange(1,5)
ax1.plot(y)


#灰色阴影,html,RGB
y=np.arange(1,5)
ax2.plot(y,'y')   #内建默认颜色
ax2.plot(y+1,color=(0.1,0.2,0.3)) #RGB
ax2.plot(y+2,'#FF00FF')  #html
ax2.plot(y+3,color='0.5') #灰色阴影


#线条样式
y=np.arange(1,5)
ax3.plot(y,'--'); # 线条
ax3.plot(y+1,'-.'); # 点线
ax3.plot(y+2,':'); # 点

#点样式,是否加线条取决于marker
y=np.arange(1,5)
ax4.plot(y,marker='o');
ax4.plot(y+1,marker='D');
ax4.plot(y+2,marker='^');
ax4.plot(y+3,'s');
ax4.plot(y+4,'p');
ax4.plot(y+5,'x');


#样式字符串,同时表示颜色,点型,线性(重要!!)
y=np.arange(1,5)
ax5.plot(y,'cx--');
ax5.plot(y+1,'kp:');
ax5.plot(y+2,'mo-.');

plt.show()

网格(grid)

y = np.arange(1,5,0.1)
plt.plot(y,y**2)
plt.grid(True,color='r',linestyle='--',linewidth='2')
# True 显示网格
# color 设置网格的颜色
# linestyle 设置线显示的类型(一共四种)
# linewidth 设置网格的宽度
plt.show()

x= np.arange(1,10,0.1)
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.grid()
ax1.plot(x,np.log(x))
plt.show()

图例(legend)

x = np.arange(1,11,1)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,x*2,label='Normal')
ax.plot(x,x*3,label='Fast')
ax.plot(x,x*4,label='Faster')
ax.plot(x,x*5,label='cool')
ax.plot(x,x*6,label='Best')
plt.legend(loc=0)
# loc= 0-10
# 0: ‘best'
# 1: ‘upper right'
# 2: ‘upper left'
# 3: ‘lower left'
# 4: ‘lower right'
# 5: ‘right'
# 6: ‘center left'
# 7: ‘center right'
# 8: ‘lower center'
# 9: ‘upper center'
# 10: ‘cente ’
# 参考 http://blog.csdn.net/helunqu2017/article/details/78641290
plt.show()

坐标轴范围调整

#ax.axis([0,10,0,100]) [x左,x右,y下,y上]
x = np.arange(-10,10,0.1)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,x**2)
ax.axis([0,10,0,100])

#plt.xlim([-5,5]) ,调整x轴坐标范围
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(x,x**2)
plt.xlim([-5,5])
#相当于 plt.xlim(xmin=-5,xmax=5)

#plt.ylim([0,60]) ,调整y轴坐标范围
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.plot(x,x**2)
plt.ylim([0,60])
#相当于 plt.ylim(ymin=0,ymax=60)

plt.show()

坐标轴刻度调整

x = np.arange(0,11,0.1)

fig1 = plt.figure()
ax1  = fig1.add_subplot(111)
ax1.plot(x,x)
#ax1.locator_params(nbins=20) #同时调整x轴与y轴
#ax1.locator_params('x',nbins=20) #只调整x轴
ax1.locator_params('y',nbins=20) #只调整y轴
plt.axis([0,10,0,10])


#日期的相关调整
start = datetime.datetime(2015,1,1)
stop  = datetime.datetime(2016,1,1)
delta = datetime.timedelta(days=1)

dates = mpl.dates.drange(start,stop,delta)
y = np.random.rand(len(dates))

fig2 = plt.figure()
ax2  = fig2.add_subplot(111)
ax2.plot_date(dates,y,linestyle='-',marker='')

#日期格式调整,不重叠
date_format= mpl.dates.DateFormatter('%Y-%m')
ax2.xaxis.set_major_formatter(date_format)
fig2.autofmt_xdate()#防止重叠

plt.show()

图中添加新坐标轴

x = np.arange(1,11,0.1)
y1 = x*x
y2 = np.log(x)

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax2 = ax1.twinx()

#ax1.set_ylable('Y1')
#ax2.set_ylable('Y2')

ax1.plot(x,y1)
ax2.plot(x,y2,'--r')

plt.show()

图中画注释符号

x =np.arange(-10,11,1)
y = x*x

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(x,y)
ax1.annotate('this is bottom',xy=(0,0),xytext=(-1.25,20),
             arrowprops=dict(facecolor='r',frac=0.2))
# annotate(s, xy, xytext=None, xycoords='data',textcoords='data'arrowprops=None, **kwargs)
# s : 描述的内容
# xy : 加描述的点
# xytext : 标注的位置,xytext=(30,-30),表示从标注点x轴方向上增加30,y轴方减30的位置
# xycoords 、textcoords :这两个参数试了好多次没弄明白,只知道 xycoords='dat给定就行,
# textcoords='offset points' 标注的内容从xy设置的点进行偏移xytext
# textcoords='data' 标注内容为xytext的绝对坐标  
# fontsize : 字体大小,这个没什么好说的
# arrowstyle : 箭头样式'->'指向标注点 '<-'指向标注内容 还有很多'-'
               # '->'   head_length=0.4,head_width=0.2
               # '-['  widthB=1.0,lengthB=0.2,angleB=None
               # '|-|'     widthA=1.0,widthB=1.0
               # '-|>'  head_length=0.4,head_width=0.2
               # '<-'   head_length=0.4,head_width=0.2
               # '<->'   head_length=0.4,head_width=0.2
               # '<|-'  head_length=0.4,head_width=0.2
               # '<|-|>'     head_length=0.4,head_width=0.2
               # 'fancy'   head_length=0.4,head_width=0.4,tail_width=0.4
               # 'simple'  head_length=0.5,head_width=0.5,tail_width=0.2
               # 'wedge'   tail_width=0.3,shrink_factor=0.5
plt.show()

图形中纯文字标注

x =np.arange(-10,11,1)
y = x*x

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(x,y)
ax1.text(-3,40,'function:y=x*x',family='fantasy',size=15,color='g',style='oblique',weight=20,bbox=dict(facecolor='r',alpha=0.2))
ax1.text(-3,30,'function:y=x*x',family='serif',size=15,color='r',style='italic',weight='black')

plt.show()

图像中画数学公式

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.set_xlim([1,7])
ax1.set_ylim([1,5])
ax1.text(2,4,r"$ alpha_i beta_j pi lambda omega $",size=15)
ax1.text(4,4,r"$ sin(0)=cos(frac{pi}{2}) $",size=15)
ax1.text(2,2,r"$ lim_{x rightarrow y} frac{1}{x^3} $",size=15)
ax1.text(4,2,r"$ sqrt[4]{x}=sqrt{y}$",size=15)
plt.show()

填充上色

x = np.linspace(0,5*np.pi,1000)
y1 = np.sin(x)
y2 = np.sin(2*x)

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

# ax1.fill(x,y1,'g',alpha=0.2)
# ax1.fill(x,y2,'r',alpha=0.2)
ax1.fill_between(x,y1,y2,where=y1>y2,facecolor='y')
ax1.fill_between(x,y1,y2,where=y1<y2,facecolor='b')
ax1.grid()

plt.show()

画填充好的图形

import matplotlib.patches as mpatches
fig,ax = plt.subplots()

xy1 = np.array([0.2,0.2])
xy2 = np.array([0.2,0.8])
xy3 = np.array([0.8,0.2])
xy4 = np.array([0.8,0.8])

circle = mpatches.Circle(xy1,0.05) #xy1 圆心
rect = mpatches.Rectangle(xy2,0.2,0.1,color='r') #xy2 左下角对应的点
polygen = mpatches.RegularPolygon(xy3,5,0.1,color='g') #xy3 圆心
ellipse = mpatches.Ellipse(xy4,0.4,0.2,color='y')

ax.add_patch(circle)
ax.add_patch(rect)
ax.add_patch(polygen)
ax.add_patch(ellipse)

plt.axis('equal')
plt.grid()
plt.show()

参考

matplotlib核心剖析(http://www.cnblogs.com/vamei/archive/2013/01/30/2879700.html#commentform)