0
点赞
收藏
分享

微信扫一扫

python数据可视化笔记(二)

小猪肥 2021-10-04 阅读 77

Matplotlib有以下重要对象:

figure (画布),ax (坐标系),axis (坐标轴)
后面的例子会用到这些对象。

文章目录















数学公式编辑可参考官方文档:
mathtext


子图subplot

import numpy as np
from matplotlib import pyplot as plt
'''
ax1=fig.add_subplot(221)
参数:
第一个参数是fig对象每行拥有的子图总数
第二个参数是fig对象每列拥有的子图总数
第三个参数是子图的位置

返回值:返回Axes实例
'''
x=np.arange(1,100)
fig=plt.figure()
axl=fig.add_subplot(221)
axl.plot(x,x)

ax2=fig.add_subplot(222)
ax2.plot(x,-x)

ax3=fig.add_subplot(223)
ax3.plot(x,x**2)

ax4=fig.add_subplot(224)
ax4.plot(x,np.log(x))
plt.show()
import numpy as np
from matplotlib import pyplot as plt

X=np.arange(1,100)

plt.subplot(221)
plt.plot(X,X)

plt.subplot(222)
plt.plot(X,-X)

plt.subplot(223)
plt.plot(X,X*X)

plt.subplot(224)
plt.plot(X,np.log(X))


生成多个figure

import numpy as np
from matplotlib import pyplot as plt

fig1=plt.figure()

ax1=fig1.add_subplot(111)

ax1.plot([1,2,3],[3,2,1])

fig2=plt.figure()

ax2=fig2.add_subplot(111)

ax2.plot([1,2,3],[1,2,3])

plt.show()


网格

import numpy as np
from matplotlib import pyplot as plt

X=np.arange(0,10,1)

fig=plt.figure()

ax=fig.add_subplot(111)

plt.plot(X,X*2)

ax.grid(color='r',linestyle='-.',linewidth='2')  #设置网格属性

plt.show()


图例

loc Value
0 智能位置
1 右上角
2 左上角
3 左下角
4 右下角
import numpy as np
from matplotlib import pyplot as plt

X=np.arange(1,100)

plt.plot(X,X*2,label='Normal')
plt.plot(X,X*3,label='Fast')
plt.plot(X,X*4,label='Faster')
plt.legend(loc=1,ncol=3)
plt.show()

#面向对象的方式:
import numpy as np
from matplotlib import pyplot as plt

X=np.arange(1,100)

fig=plt.figure()

ax=fig.add_subplot(111)

l=plt.plot(X,X,label='label')

ax.legend()
#ax.legend(['ax legend'])

plt.show()


坐标轴范围

import numpy as np
from matplotlib import pyplot as plt

X=np.arange(-10,11,1)

fig=plt.figure()
ax=fig.add_subplot(111)
l=plt.plot(X,X*X)
plt.axis([-6,6,10,60])
#plt.xlim(-6,6)
#plt.xlim(xmin=-6)


plt.show()


坐标轴刻度

import numpy as np
from matplotlib import pyplot as plt

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

plt.plot(x,x)

ax=plt.gca()  #获取当前图像的坐标轴

ax.locator_params(nbins=10)   #(版本不同,效果有细微差别)把坐标轴8等份,因为坐标轴两边-10,10还有空白,加起来就10份了

#也可以指定某个轴,比如:ax.locator_params('x',nbins=10)
plt.show()

import numpy as np
from matplotlib import pyplot as plt
import datetime
import matplotlib as mpl
fig=plt.figure()

#设置日期序列
start=datetime.datetime(2018,9,30)
stop=datetime.datetime(2019,9,30)

delta=datetime.timedelta(days=1)

dates=mpl.dates.drange(start,stop,delta)

y=np.random.rand(len(dates))

ax=plt.gca()

ax.plot_date(dates,y,linestyle='-',marker='')

#设置日期显示格式(x轴显示格式)
date_format=mpl.dates.DateFormatter('%Y-%m-%d')

ax.xaxis.set_major_formatter(date_format)
#使x轴显示的日期自适应窗口大小
fig.autofmt_xdate()

plt.show()


添加坐标轴

import numpy as np
from matplotlib import pyplot as plt

x=np.arange(2,20,1)

y1=x*x

y2=np.log(x)

fig=plt.figure()

ax1=fig.add_subplot(111)

ax1.plot(x,y1)

ax1.set_ylabel('Y1')

ax2=ax1.twinx()  #ax2和ax1共x轴

ax2.plot(x,y2,'r')

ax2.set_ylabel('Y2')

ax1.set_xlabel('Compare Y1 and Y2')

plt.show()


添加注释

import numpy as np
from matplotlib import pyplot as plt

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

y=x*x

plt.plot(x,y)
'''
参数:
xy为箭头头部的坐标
xytext为箭头尾部(文字)的坐标
arrowprops指定箭头的属性
其中facecolot是箭头颜色,frac是箭头占整个箭头符号的比例
headwidth为箭头头部的宽度,width为键身的宽度
'''
plt.annotate('this is the bottom',xy=(0,4),xytext=(0,30),
             arrowprops=dict(facecolor='g',frac=0.2,headwidth=30,width=18))

plt.show()


添加文字

import numpy as np
from matplotlib import pyplot as plt

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

y=x*x

plt.plot(x,y)
'''
plt.text()参数:
前面两个数字是要显示文字的起始坐标
'y=x*x'是要显示的文字
family可以设置字体,
常用字体包括:‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, or ‘monospace’
style设置风格,比如斜体
weight设置字体粗细(这个参数可以是数字0~1000,也可以是文字:ultralight,light,normal,regular,book,medium,roman,semibold,demibold,demi,bold,heavy,extra bold,black)
bbox设置一个矩形框包住要显示的文字,其中alpha是透明度
'''
plt.text(-1,40,'y=x*x',family='fantasy',size=20,color='r',style='italic',weight='demi',
         bbox=dict(facecolor='r',alpha=0.2))

plt.show()


显示数学公式

公式参考:mathtext

import numpy as np
from matplotlib import pyplot as plt

fig=plt.figure()

ax=fig.add_subplot(111)

ax.set_xlim([1,7])

ax.set_ylim([1,5])

#数学公式书写要用$$包括
ax.text(2,3,r'$\sin(0)=\cos(\frac{\pi}{2})$',size=30)

plt.show()


区域填充

import numpy as np
from matplotlib import pyplot as plt

x=np.linspace(0,5*np.pi,1000)

y1=np.sin(x)

y2=np.sin(2*x)

# plt.plot(x,y1)
# plt.plot(x,y2)

# alpha是透明度,'b'是蓝色,'r'是红色
plt.fill(x,y1,'b',alpha=0.3)

plt.fill(x,y2,'r',alpha=0.3)

plt.show()

import numpy as np
from matplotlib import pyplot as plt

x=np.linspace(0,5*np.pi,1000)

y1=np.sin(x)

y2=np.sin(2*x)

# plt.plot(x,y1)
# plt.plot(x,y2)

fig=plt.figure()

ax=plt.gca()

ax.plot(x,y1,color='r')
ax.plot(x,y2,color='black')
#因为x取值是离散的,所以当x间距较大时,可能会出现空白区域,参数 interpolate设为True的意义就是让这些空白区域也可以显色
ax.fill_between(x,y1,y2,where=y1>y2,facecolor='yellow',interpolate=True)
ax.fill_between(x,y1,y2,where=y2>y1,facecolor='r',interpolate=True)

plt.show()


生成形状

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches

'''
fig, ax = plt.subplots()等价于fig, ax = plt.subplots(ncols=1, nrows=1)
等价于
fig=plt.figure()
ax=ax = fig.add_subplot(111)
'''
fig,ax=plt.subplots()

'''
使用array()函数可以将列表转化为数组

'''
xy1=[0.2,0.2]
#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)
ax.add_patch(circle)

rect=mpatches.Rectangle(xy2,0.2,0.1,color='r')
ax.add_patch(rect)

ellipse=mpatches.Ellipse(xy4,0.4,0.2,color='y')
ax.add_patch(ellipse)

# 第二个参数设为5表示边数为5,0.1表示图形中心到顶点的距离(类比圆的半径)
polygon=mpatches.RegularPolygon(xy3,5,0.1,color='g')
ax.add_patch(polygon)

#设置横纵坐标比例相等,否则会显示椭圆
plt.axis('equal')

#添加网格
plt.grid()

plt.show()

更多的形状


样式美化

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import patches as mpatches
'''
# print(plt.style.available)  #样式
返回:
['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 
'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 
'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks',
 'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'Solarize_Light2', 'tableau-colorblind10', '_classic_test']
'''

#设置样式:
plt.style.use('dark_background')

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)

# # plt.rcParams['axes.color_cycle'] 为默认的颜色循环
# ncolors=len(plt.rcParams['axes.color_cycle'])

#获取颜色循环
colors = [color['color'] for color in list(plt.rcParams['axes.prop_cycle'])]


shift=np.linspace(0,10,7)

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=colors[1])
ax3.bar(x+2*width,y2,width,color=colors[2])

for  color in colors:
    xy=np.random.normal(size=2)
    ax4.add_patch(plt.Circle(xy,radius=0.3,color=color))

ax4.axis('equal')
ax4.grid()

plt.show()



极坐标

import numpy as np
from matplotlib import pyplot as plt

r=np.arange(1,6,1)

theta=[np.pi*i/2 for i in range(5)]

#设置极坐标系
ax=plt.subplot(111,projection='polar')

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

ax.grid(True)

plt.show()

'''
2019-10-15更新
'''

坐标轴标注

我们有时需要标注x轴是什么,y轴是什么,还需要给x,y轴设置标签,比如下面的例子:

import numpy as np
from matplotlib import pyplot as plt
def func(x):
    return -(x-3)*(x-7)+9

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

fig,ax=plt.subplots()

plt.plot(x,y,'r',linewidth=2)
a=2
b=8

ax.set_xticks([a,b])  # 设置x标签
ax.set_yticks([])     # 设置y标签(这里为空)

ax.set_xticklabels(['$x_1$','$x_2$'])  #设置x标签的显示形式
plt.figtext(0.9,0.05,'$x$')            #前面两个参数的范围在0,1之间,是相对窗口的位置,而不是坐标轴的位置,可以看后面生成的图
plt.figtext(0.1,0.9,'$y$')
plt.show()

举报

相关推荐

0 条评论