半小时拿下Python数据处理之Matplotlib篇


import numpy as np
import os
import matplotlib.pyplot as plt
#notebook模式下
%matplotlib inline

matplotlib三种代码风格

pyplot
x=np.arange(0,10,1)
y=np.random.randn(len(x))
plt.plot(x,y) #绘制以x为横坐标,y为纵坐标的折线图
plt.title('pyplot')
plt.show()

pylab
#pylab不推荐使用
from pylab import *
x=arange(0,10,1)
y=randn(len(x))
plot(x,y) #绘制以x为横坐标,y为纵坐标的折线图
title('pylab')
show()

Object Oriented

在matplotlib中,整个图像为一个Figure对象。在Figure对象中可以包含一个,或者多个Axes对象。每个Axes对象都是一个拥有自己坐标系统的绘图区域。其逻辑关系如下:
整个图像是fig对象。我们的绘图中只有一个坐标系区域,也就是ax。此外还有以下对象。

  • Data: 数据区,包括数据点、描绘形状
  • Axis: 坐标轴,包括 X 轴、 Y 轴及其标签、刻度尺及其标签
  • Title: 标题,数据图的描述
  • Legend: 图例,区分图中包含的多种曲线或不同分类的数据
  • 其他的还有图形文本 (Text)、注解 (Annotate)等其他描述

    Title为标题。Axis为坐标轴,Label为坐标轴标注。Tick为刻度线,Tick Label为刻度注释。各个对象之间有下面的对象隶属关系:
# 推荐使用
x=np.arange(0,10,1)
y=np.random.randn(len(x))
fig=plt.figure() #定义图像的对象
ax=fig.add_subplot(111) #定义坐标系区域
ax.plot(x,y) #绘制以x为横坐标,y为纵坐标的折线图
ax.set_title('object oriented')
plt.show()

子图

x = np.arange(1,100)

fig = plt.figure()
ax1 = fig.add_subplot(221) # 定义2*2个子图(左一)
ax1.plot(x,x) # 绘制左一折线图

ax2 = fig.add_subplot(222)
ax2.plot(x,-x) # 绘制右一折线图(右一)

ax3 = fig.add_subplot(223)
ax3.plot(x,x*x) # 绘制左二折线图(左二)

ax4 = fig.add_subplot(224)
ax4.plot(x,np.log(x)) # 绘制右二折线图(右二)

plt.show()

x = np.arange(1,100)
plt.subplot(221) # 第一行的左图
plt.plot(x,x)
plt.subplot(222) # 第一行的右图
plt.plot(x,-x)
plt.subplot(212) # 第二整行
plt.plot(x,x*x)
plt.show()

#简化写法
fig,axes = plt.subplots(ncols=2,nrows=2) #定义子图为两行两列
ax1,ax2,ax3,ax4 = axes.ravel() #按照先行再列的顺序分配子图

x = np.arange(1,100)
ax1.plot(x,x)
ax2.plot(x,-x)
ax3.plot(x,x*x)
ax4.plot(x,np.log(x))
plt.show()

多图

fig1 = plt.figure() # plt派生一个图对象
ax1 = fig1.add_subplot(111)
ax1.plot([1,2,3],[3,2,1])

fig2 = plt.figure() # plt派生另一个图对象
ax2 = fig2.add_subplot(111)
ax2.plot([1,2,3],[1,2,3])

plt.show() # plt统一显示

散点图(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()

颜色与样式

颜色

样式
  • 线条样式

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XuExvyUA-1589898432948)(http://image.yigouai.cn/2ddb1d67c59e9bedc5366fff124efdd8.png)]

  • 标记样式

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()

美化图形

# 采用ggplot绘画风格
plt.style.use('ggplot')

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


x,y = np.random.normal(size=(2,100))
ax1.plot(x,y,'o')

x = np.arange(0,10)
y = np.arange(0,10)
ncolors = len(plt.rcParams['axes.color_cycle'])
shift = np.linspace(0,10,ncolors)
for s in shift:
    ax2.plot(x,y+s,'-')

x = np.arange(5)
y1,y2,y3 = np.random.randint(1,25,size=(3,5))
width = 0.25

ax3.bar(x,y1,width)
ax3.bar(x+width,y2,width,color='r')
ax3.bar(x+2*width,y3,width,color='g')

for i,color in  enumerate(plt.rcParams['axes.color_cycle']):
    xy = np.random.normal(size=2)
    ax4.add_patch(plt.Circle(xy,radius=0.3,color=color))
ax4.axis('equal')

plt.show()

极坐标

plt.style.use('ggplot')

r = np.arange(1,6)
theta = [0,np.pi/2,np.pi,np.pi*3/2,2*np.pi]

ax = plt.subplot(111,projection='polar')

ax.plot(theta,r,color='r',linewidth=2)

ax.grid(True)

plt.show()

函数积分图

def func(x):
    return -(x-2)*(x-8)+40

x = np.linspace(0,10)
y = func(x)

fig,axes = plt.subplots()
axes.plot(x,y,'r',linewidth=2)
a = 2
b = 9
axes.set_xticks([a,b])
axes.set_yticks([])
axes.set_xticklabels([r'$a$','$b$'])

ix = np.linspace(a,b)
iy = func(ix)
ixy = zip(ix,iy)

verts = [(a,0)]+list(ixy)+[(b,0)]
poly = Polygon(verts,facecolor='0.8',edgecolor='0.5')
axes.add_patch(poly)

plt.figtext(0.9,0.07,r'$x$')
plt.figtext(0.1,0.9,r'$y$')

x_math = (a+b)*0.5
y_math = 35

plt.text(x_math,y_math,r'$\int_a^b(-(x-2)*(x-8)+40)dx$',fontsize=10,horizontalalignment='center')

plt.show()

二维散点概率分布图

plt.style.use('ggplot')

x = np.random.randn(200)
y = x + np.random.randn(200)*0.5

margin_border = 0.1
width = 0.6
margin_between = 0.02
height = 0.2

left_s = margin_border
bottom_s = margin_border
height_s = width
width_s = width

left_x = margin_border
bottom_x = margin_border+width+margin_between
height_x = height
width_x = width

left_y = margin_border+width+margin_between
bottom_y = margin_border
height_y = width
width_y = height

plt.figure(1,figsize=(8,8))
rect_s = [left_s,bottom_s,width_s,height_s]
rect_x = [left_x,bottom_x,width_x,height_x]
rect_y = [left_y,bottom_y,width_y,height_y]

axScatter = plt.axes(rect_s)
axHisX = plt.axes(rect_x)
axHisY = plt.axes(rect_y)
axHisX.set_xticks([])
axHisY.set_yticks([])

axScatter.scatter(x,y)

bin_width = 0.25
xymax = np.max([np.max(np.fabs(x)),np.max(np.fabs(y))])

lim =int(xymax/bin_width+1) * bin_width

axScatter.set_xlim(-lim,lim)
axScatter.set_ylim(-lim,lim)

bins = np.arange(-lim,lim+bin_width,bin_width)

axHisX.hist(x,bins=bins)
axHisY.hist(y,bins=bins,orientation='horizontal')

axHisX.set_xlim(axScatter.get_xlim())
axHisY.set_ylim(axScatter.get_ylim())

plt.title('Scatter and Hist')
plt.show()

完整的绘制程序综合

import numpy as np
import matplotlib.pyplot as plt
from pylab import *

# 定义数据部分
x = np.arange(0., 10, 0.2)
y1 = np.cos(x)
y2 = np.sin(x)
y3 = np.sqrt(x)

# 绘制 3 条函数曲线
plt.plot(x, y1, color='blue', linewidth=1.5, linestyle='-', marker='.', label=r'$y = cos{x}$')
plt.plot(x, y2, color='green', linewidth=1.5, linestyle='-', marker='*', label=r'$y = sin{x}$')
plt.plot(x, y3, color='m', linewidth=1.5, linestyle='-', marker='x', label=r'$y = \sqrt{x}$')

# 坐标轴上移
ax = plt.subplot(111)
ax.spines['right'].set_color('none')     # 去掉右边的边框线
ax.spines['top'].set_color('none')       # 去掉上边的边框线

# 移动下边边框线,相当于移动 X 轴
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))

# 移动左边边框线,相当于移动 y 轴
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

# 设置 x, y 轴的取值范围
plt.xlim(x.min()*1.1, x.max()*1.1)
plt.ylim(-1.5, 4.0)

# 设置 x, y 轴的刻度值
plt.xticks([2, 4, 6, 8, 10], [r'2', r'4', r'6', r'8', r'10'])
plt.yticks([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0],
    [r'-1.0', r'0.0', r'1.0', r'2.0', r'3.0', r'4.0'])

# 添加文字
plt.text(4, 1.68, r'$x \in [0.0, \ 10.0]$', color='k', fontsize=15)
plt.text(4, 1.38, r'$y \in [-1.0, \ 4.0]$', color='k', fontsize=15)

# 特殊点添加注解
plt.scatter([8,],[np.sqrt(8),], 50, color ='m')  # 使用散点图放大当前点
plt.annotate(r'$2\sqrt{2}$', xy=(8, np.sqrt(8)), xytext=(8.5, 2.2), fontsize=16, color='#090909', arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=0.1', color='#090909'))

# 设置标题、x轴、y轴
plt.title(r'$the \ function \ figure \ of \ cos(), \ sin() \ and \ sqrt()$', fontsize=19)
plt.xlabel(r'$the \ input \ value \ of \ x$', fontsize=18, labelpad=88.8)
plt.ylabel(r'$y = f(x)$', fontsize=18, labelpad=12.5)

# 设置图例及位置
plt.legend(loc='up right')
# plt.legend(['cos(x)', 'sin(x)', 'sqrt(x)'], loc='up right')

# 显示网格线
plt.grid(True)

# 显示绘图
plt.show()

绘制三维图形

首先补充一下numpymeshgrid函数的用法。具体含义如下图所示
函数的用法

绘制3D曲面图
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D #导入三维绘制工具箱

fig = plt.figure() # 创建一个绘图对象
ax = Axes3D(fig) # #用这个绘图对象创建一个Axes对象(有3D坐标)
X = np.arange(-4, 4, 0.25) #创建从-4到4,步长为0.25的arange对象
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y) #用这两个arange对象中的可能取值一一映射去扩充为所有可能的取样点
R = np.sqrt(X**2 + Y**2) #函数表示
Z = np.sin(R)
# 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface)
# rstride和cstride表示行列隔多少个取样点建一个小面
# cmap表示绘制曲面的颜色
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')

plt.show()

绘制三维散点图
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

data = np.random.randint(0, 255, size=[40, 40, 40])
#data = np.random.randint(0, 255, size=[3,40, 40, 40]) #四维
x, y, z = data[0], data[1], data[2]
#x, y, z = data[0,1], data[0,2], data[0,3] #取值时需要[0,index]
ax = plt.subplot(111, projection='3d')  # 创建一个三维的绘图工程
#  将数据点分成三部分画,在颜色上有区分度
ax.scatter(x[:10], y[:10], z[:10], c='y')  # 绘制数据点
ax.scatter(x[10:20], y[10:20], z[10:20], c='r')
ax.scatter(x[30:40], y[30:40], z[30:40], c='g')

ax.set_zlabel('Z')  # 坐标轴
ax.set_ylabel('Y')
ax.set_xlabel('X')
plt.show()

保存图像为矢量图

用python的matplotlib画出的图,一般是需要保存到本地使用的。如果是用show()展出的图,再右键保存,这样的图是失帧而非矢量的。
保存矢量图的方法是使用函数savefig(),接口定义如下:


savefig(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None,
        transparent=False, bbox_inches=None, pad_inches=0.1,
        frameon=None, metadata=None)

可以看到它的参数还是很多的,但保存矢量图只需要用到三个参数,即

  • fname: 文件名称,
  • dpi: 每英寸点的分辨率。根据Wiley的关于图像的指导准则,一般折线图的dpi设置为600,而图像的dpi设置为300。
  • format: 文件格式。支持的格式包括:.eps, .jpeg, .jpg, .pdf, .pgf, .png, .ps, .raw, .rgba, .svg, .svgz, .tif, .tiff。

一个完整的保存矢量图的代码为:


import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x1 = np.random.uniform(-10, 10, size=20)
x2 = np.random.uniform(-10, 10, size=20)

number = []
x11 = []
x12 = []
for i in range(20):
    number.append(i+1)
    x11.append(i+1)
    x12.append(i+1)
plt.figure(1)
# you can specify the marker size two ways directly:
plt.plot(number, x1, 'bo', markersize=20,label='a')  # blue circle with size 20
plt.plot(number, x2, 'ro', ms=10,label='b')  # ms is just an alias for markersize
 
lgnd=plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0,numpoints=1,fontsize=10)
lgnd.legendHandles[0]._legmarker.set_markersize(16)
lgnd.legendHandles[1]._legmarker.set_markersize(10)
 
plt.show()
 
fig.savefig('scatter.eps',dpi=600,format='eps')

保存矢量图的具体代码为最后一行 ,此处保存的名称为scatter,格式为eps,分辨率为600。

绘制函数图显示并保存为矢量图



import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

def f(x,eta):
    mask = x < 0.5
    y = (np.power(2.0*x,1.0/(eta+1))-1.0)*mask + (1.0 - np.power(2.0*(1-x),1.0/(1+eta)))*(1-mask)
    return y

x = np.linspace(0.01, 0.99, 100)

y1 = f(x,1)
y2 = f(x,2)
y3 = f(x,4)
y4 = f(x,8)
 
plt.plot(x, y1,label=r'$\eta=1$')
plt.plot(x, y2,label=r'$\eta=2$')
plt.plot(x, y3,label=r'$\eta=4$')
plt.plot(x, y4,label=r'$\eta=8$')

 
# plt.title('line chart')
plt.xlabel(r'$\mu$')
plt.ylabel(r'$\beta$')

plt.legend(loc=0)

plt.show()

fig.savefig('mutation.pdf',dpi=600,format='pdf')


参考

matplotlib核心剖析

Numpy中Meshgrid函数介绍及2种应用场景


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值