数据可视化分析——matplotlib详细介绍

数据可视化分析——matplotlib详细介绍

1.颜色和样式:

  1. 颜色
    八种内建默认颜色缩写:
    b:blue
    g: green
    r: red
    c: cyan
    m: magenta
    y: yellow
    k: black
    w: white
    其他颜色表示方法:
    灰色阴影
    html 十六进制
    RGB元组
  2. 23种形状。注意不同点形状默认使用不同颜色。
    在这里插入图片描述
  3. 线形
plt.plot(y, '--')
plt.plot(y+1,'-.')
plt.plot(y+2, ':')
plt.plot(y+3,'-')
  1. 样式字符串
    可以将颜色,点形,线形写成一个字符串,如
    cx–
    mo:
    kp-

2.面向对象VS Matiab Style

  1. 三种方式
    1. pyplot:经典高层封装,到目前为止,我们所用的都是pyplot
      优点:简单易用,交互使用时方便,可以根据命令实时作图
      缺点:底层定制能力不足
    2. pyplab:将Matplotlib和Numpy合并的模块,模拟Matlab的编程环境
      完全封装,环境最接近Matlab,不推荐使用
    3. 面向对象的方式: Matplotlib的精髓,更基和底层的方式
      优点:接近Matplotlib基础和底层的方式,定制能力强。
      缺点:难度大
  2. 常用模式:之前写的
  3. 面向对象的方式:
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,10,1)
y = np.random.randn(len(x))

fig = plt.figure()   # 生成一个画布对象
ax = fig.add_subplot(111)  # 生成一个坐标轴对象
l,= plt.plot(x,y)    # 画图
t = ax.set_title('object oriented')  #定一下他的title

3.子图-subplot

  1. Matplotlib三级对象:
    FigurCanvas
    Figure
    Axes
  2. fig = plt.figure()
    ax = fig.add_subplot(111)
    返回Axes实例
    参数一:子图总行数 参数二:子图总列数 参数三:子图位置
    在这里插入图片描述
x = np.arange(1,100)
fig = plt.figure()
ax1 = fig.add_subplot(221)
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))
  1. 生成多张图:多图-figure
import numpy as np
import matplotlib.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])

4.网格:

import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1,5)
plt.plot(y,y*2)
plt.grid(True)  # 打开网格
plt.grid(color = 'g')  # 定制化网格
plt.grid(linewidth = '2')  # 宽度
plt.grid(linestyle = '--')  # 线形
  1. 面向对象版:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
x = np.arange(0,10,1)
ax = fig.add_subplot(111)
plt.plot(x,x*2)
ax.grid(color = 'g')

5.图例_legend:

  1. plt方式:
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1,11,1)
plt.plot(x,x*2,label = 'Normal')   #只有命名没有图例
plt.plot(x,x*3,label = 'Fast')
plt.plot(x,x*4,label = 'Faster') 
plt.legend()  #图例的添加

loc(图例位置)0:best  1:upper right  2:upper left  3:lower left  4:lower right
ncol(图例分成几列)1112:213:3个一列(变得扁平)
  1. 面向对象方式:
x = np.arange(1,11,1)
fig = plt.figure()
ax = fig.add_subplot(111)
l, = plt.plot(x,x,label = 'Inline label')
ax.legend()

6.坐标轴:

  1. 坐标轴范围:
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10,11,1)
plt.plot(x,x*x)
#改变x轴为-10——10 y轴为0——100
plt.axis([-10,10,30,90])
#改变x轴
plt.xlim()
xlim(xmin = 5,xmax = 10)
#改变y轴
plt.ylim()
  1. 坐标轴刻度:
x = np.arange(1,11,1)
plt.plot(x,x)
ax = plt.gca()   #获取当前的坐标轴
ax.locator_params('x',nbins = 20)

plt和面向对象的区别
特别提一下日期:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import datetime

fig = plt.figure()
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))
ax = plt.gca()
ax.plot_date(dates,y,linestyle = '-',marker = '')
date_format = mpl.dates.DateFormatter('%Y-%m')
ax.xaxis.set_major_formatter(date_format)
fig.autofmt_xdate()
  1. 添加坐标轴
    1. plt方法:
    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.arange(2,20,1)
    y1 = x*x
    y2 = np.log(x)
    plt.plot(x,y1)
    plt.twinx()   # 添加一条坐标轴
    plt.plot(x,y2,'r')
    plt.show()
    
    1. 面向对象:
    import numpy as np
    import matplotlib.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.plot(x,y2,'r')
    ax2.set_xlabel('Compare Y1 and Y2')
    plt.show()
    

在这里插入图片描述

7.注释

  1. 着重强调某一个地方的提示
# 注释
import matplotlib.pyplot as plt
import numpy as np

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

plt.plot(x,y)
# 注释使用annotate函数
# 第一个参数:注释的内容
# 第二个参数:xy填写箭头的坐标
# 第三个参数:xytext填写注释内容的坐标
# 第四个参数arrowprops定义注释箭头信息,其中facecolor表示箭头颜色,frac表示箭头的头占的比例
# headwidth定义箭头的宽度,width表示箭身的宽度
plt.annotate('this is the bottom',xy=(0,1),xytext=(0,20),
             arrowprops=dict(facecolor='r',frac=0.2,headwidth=20,width=10))
plt.show()

8.文字标注:

# 在图中生成一段文字
import numpy as np
import matplotlib.pyplot as plt

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

plt.plot(x,y)
# 使用text函数在图中生成一段文字
# 前两个参数是文字起始点的横纵坐标,第三个参数是文字
# 第四个参数是family表示文字字体,
# size参数定义字体的大小,color定义颜色,style定义字体格式,weight定义字体的粗细
# bbox(箱体)定义一个框用来框住字体,里面有facecolor参数定义箱体颜色,alpha定义透明度
plt.text(-3,30,'function:y=x*x',family='fantasy',size=20,color='g',
         style='italic',weight=500,bbox=dict(facecolor='r',alpha=0.2))
plt.show()

9.Tex公式:

  1. 主要是绘制数学公式:
# Tex公式
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
# 设置x与y坐标轴
ax.set_xlim([1,7])
ax.set_ylim([1,5])

ax.text(2,4,r"$ \alpha_i \beta_j \pi \lambda \omega $",size=25)
ax.text(4,4,r"$ \sin(0)=\cos(\frac{\pi}{2}) $",size=25)
ax.text(2,2,r"$ \lim_{x \rightarrow y} \frac{1}{x^3} $",size=25)
ax.text(4,2,r"$ \sqrt[4]{x}=\sqrt{y} $",size=25)
plt.show()

在这里插入图片描述

10.工具栏:

11.区域填充:

# 区域填充
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,5*np.pi,1000)
y1 = np.sin(x)
y2 = np.sin(2*x)
# 填充图形与x轴相交的部分
plt.fill(x,y1,'b',alpha=0.3)
plt.fill(x,y2,'r',alpha=0.3)

plt.show()

面向对象+fill_between

# 区域填充--面向对象
import numpy as np
import matplotlib.pyplot as plt

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

fig = plt.figure()
ax = plt.gca()
ax.plot(x,y1,color='r')
ax.plot(x,y2,color='black')
# 根据条件分别填充where
# interpolate=True表示当x离散的厉害时,对空白部分自动填充
ax.fill_between(x,y1,y2,where=y1>=y2,facecolor='y',interpolate=True)
ax.fill_between(x,y1,y2,where=y1<y2,facecolor='g',interpolate=True)

plt.show()

12.形状:

# 形状
import numpy as np
import matplotlib.pyplot as plt
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)
# 把圆添加到画幕上
ax.add_patch(circle)

# 画矩形 左下角点的坐标-长-宽-颜色
rect = mpatches.Rectangle(xy2,0.2,0.1,color='r')
ax.add_patch(rect)

# 画多边形 图形中心-边数-中心到顶点长度-颜色
polygon = mpatches.RegularPolygon(xy3,5,0.1,color='g')
ax.add_patch(polygon)

# 画椭圆形 圆心-长直径-短直径-颜色
ellipse = mpatches.Ellipse(xy4,0.4,0.2,color='y')
ax.add_patch(ellipse)
# 调整x轴y轴比例
plt.axis('equal')
# 网格
plt.grid()

plt.show()

13.样式-美化图形

In [14]: x=np.array([[1,2],[3,4]])

# flattenh函数和ravel函数在降维时默认是行序优先
In [15]: x.flatten()
Out[15]: array([1, 2, 3, 4])

In [17]: x.ravel()
Out[17]: array([1, 2, 3, 4])
# 样式-美化
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
# 生成两行两列的子图
fig,axes = plt.subplots(ncols=2,nrows=2)
# 将四个子图的坐标轴分别fu为四个对象
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)
# 循环颜色的数目,axes.prop_cycle来控制颜色循环
ncolors = len(plt.rcParams['axes.prop_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, color=mpl.rcParams['axes.prop_cycle'].by_key()['color'][0])
ax3.bar(x + width, y2, width, color=mpl.rcParams['axes.prop_cycle'].by_key()['color'][1])
ax3.bar(x + 2 * width, y3, width, color=mpl.rcParams['axes.prop_cycle'].by_key()['color'][2])

#添加圆形
print(plt.rcParams['axes.prop_cycle'])
# python其实提供了内置的enumerate函数可以同时获得索引和值
# np.random.normal(size,loc,scale)
for i, xcolor in enumerate(plt.rcParams['axes.prop_cycle']):
    xy = np.random.normal(size=2)
    ax4.add_patch(plt.Circle(xy, radius=0.3, color=xcolor['color']))
# x、y调成对称
ax4.axis('equal')

plt.show()

plt.style.use(‘ggplot’)
在这里插入图片描述

14.极坐标:

# 极坐标
import numpy as np
import matplotlib.pyplot as plt
# 半径
r = np.arange(1,6,1)
# 角度
theta = [0,np.pi/2,np.pi,3*np.pi/2,2*np.pi]
# projection='polar'表示将坐标投影为极坐标
ax = plt.subplot(111, projection = 'polar')

ax.plot(theta,r,color='r',linewidth=3)
# 网格
ax.grid(True)

plt.show()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值