一文搞定matplotlib数据可视化

matplotlib的绘图方式

  1. 使用pyplot:简单易用,可以实时交互
  2. 使用pylab:对matplotlib和numpy进行了封装,类似Matlab的变成方式.(一般不推荐使用)
  3. 面向对象:定制能力强.

1、使用pylab方式

对numpy和matplotlib进行了封装,所以直接调用函数就可以,所以形式和matlab类似
from pylab import *

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

plot(x, y)
title("pylab")
show()

在这里插入图片描述

2、pyplot方式

import numpy as np
import matplotlib.pyplot as plt

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

plt.plot(x, y)
plt.title("pyplot")
plt.show()

在这里插入图片描述

3、面向对象的方式

  • 创建画布对象,可以创建多个画布
  • 创建坐标轴对象
  • 在坐标轴对象上绘图
import numpy as np
import matplotlib.pyplot as plt

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

fig = plt.figure(0)      # 创建画布
ax = fig.add_subplot(111) # 创建坐标轴对象

plt.plot(x, y)
ax.set_title("object oriented")

plt.show()

在这里插入图片描述

基本图形绘制

1、散点图绘制

plt.scatter参数说明:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html?highlight=scatter#matplotlib.pyplot.scatter

import matplotlib.pyplot as plt
import numpy as np

x = np.array([i for i in range(10)])
y = x**2
plt.scatter(x, y,)        # 绘制散点图
plt.show()

在这里插入图片描述

2、折线图

import matplotlib.pyplot as plt
import numpy as np

x = np.array([i for i in range(10)])
y = np.array([3, 4, 6, 5, 8, 9, 12, 2, 5, 8])
plt.plot(x, y, "r-")
plt.show()

在这里插入图片描述

3、条形图

plt.bar常用参数说明:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html?highlight=bar#matplotlib.pyplot.bar

  • x: x轴的坐标

  • height: y轴的数据

  • width: 块的宽度

  • bottom: 底部的基数

  • align:条形图的块儿的对齐方式,默认居中

    • ‘center’: 居中
    • ‘edge’: 靠左对齐

绘制水平条形图使用ply.barh

import numpy as np
import matplotlib.pyplot as plt

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

index = np.arange(N)

fig = plt.figure(0)

ax1 = fig.add_subplot(141)
plt.bar(index, y)
plt.title("default")
plt.ylim([0, 100])

ax2 = fig.add_subplot(142)
plt.bar(index, y, width=0.5, bottom=50) # 调整底部基数和条形宽度
plt.title("bottom-width")
plt.ylim([0, 100])

ax3 = fig.add_subplot(143)
plt.bar(index, y, align='edge')        # 添加align效果
plt.title("balign")
plt.ylim([0, 100])

ax4 = fig.add_subplot(144)
plt.barh(y, index)                     # 水平效果
plt.title("horizontal")

plt.show()

在这里插入图片描述

4、直方图

plt.hist:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html?highlight=hist#matplotlib.pyplot.hist

  • x: x轴坐标
  • bins: 将数据分成的组数
  • density: bool类型,设置y轴是否归一化,默认不做归一化
import numpy as np
import matplotlib.pyplot as plt

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

fig = plt.figure(0)

ax1 = fig.add_subplot(141)
plt.hist(x, bins=100, color="red", density=True)

ax2 = fig.add_subplot(142)
plt.hist(x, bins=10, color="red", density=True)

ax3 = fig.add_subplot(143)
plt.hist(x, bins=10, color="red", density=False)

plt.show()

在这里插入图片描述

plt.hist2d:绘制二维分布,用颜色来表示密度https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist2d.html?highlight=hist2d#matplotlib.pyplot.hist2d

import numpy as np
import matplotlib.pyplot as plt

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

plt.hist2d(x, y, bins=40, cmap='OrRd')
plt.colorbar()
plt.show()

在这里插入图片描述

5、饼状图

plt.pie:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pie.html?highlight=pie#matplotlib.pyplot.pie

  • autopct: 显示百分比
  • explode: 某一个块离圆心的距离,为一个数组,对应每一个label
import numpy as np
import matplotlib.pyplot as plt

labels = 'A', 'B', 'C', 'D'
fracs = [15, 30, 45, 10]

explode = [0.2, 0.2, 0.2, 0.3]

plt.axes(aspect=1)                                  # 将x和y轴的比例设置为1:1,这样就可以画出正圆,不然可能为椭圆
plt.pie(x=fracs, labels=labels, autopct='%.0f%%', explode=explode, shadow=True)   # autopct:显示百分比
plt.show()

在这里插入图片描述

6、箱型图

plt.boxplot:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.boxplot.html?highlight=boxplot#matplotlib.pyplot.boxplot

  • sym: 控制异常点的形状
  • whis: 控制上下边界的范围
  • labels: 同事绘制多个箱型图
import numpy as np
import matplotlib.pyplot as plt

x = np.random.seed(100)
data = np.random.normal(size=(1000, 4), loc=0, scale=1)
labels = ['A', 'B', 'C', 'D']
plt.boxplot(data, sym='+', whis=1.5, labels=labels)
plt.show()

在这里插入图片描述

7、热力图

直接调用plt.imshow(),传入需要显示的数组即可。通过cmap传入colormapla改变颜色

import numpy as np
import matplotlib.pyplot as plt

a = np.array([[1 ,2, 3], [2, 3, 4], [3, 4, 5]])
plt.imshow(a, cmap='plasma')
plt.colorbar()
plt.show()

在这里插入图片描述

8、极坐标

在创建坐标轴对象时设置属性projection='polar’

import numpy as np
import matplotlib.pyplot as plt

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

ax = plt.subplot(111, projection='polar')
plt.plot(theta, r, linewidth=3, c='r')
ax.grid(True)
plt.show()

在这里插入图片描述

样式设置

1、子图和多图

子图:在同一个图上绘制多个子图

  • 生成figure对象:fig = plt.figure(0)
  • 添加axes实例: ax = fig.add_subplot(111) 这三个参数分别表示行数,列数,和子图的序列号

多图:在不同的画布上绘制图形,就是生成多个figure对象

2、网格

grid:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.grid.html?highlight=grid#matplotlib.pyplot.grid

  • color: 设置颜色
  • linewidth: 设置线宽
  • linestyle: 设置线性
  • axis: 设置网格的轴
  • 使用plt的方式绘制网格:直接调用plt.grid(True)函数,可以通过参数color,linewidth,linestyle设置颜色、线宽和线。
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1, 5)
plt.plot(x, x*2)
plt.grid(True)
plt.show()

在这里插入图片描述

  • 使用面向对象的方式绘制网格:使用坐标轴对象调用grid来绘制网格,同理可以通过上述参数设置相关内容
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1, 5)

fig = plt.figure("grid")
ax = fig.add_subplot(111)
plt.plot(x, x*2)
ax.grid(color='r', linestyle='--', which ='both')
plt.show()

在这里插入图片描述

3、图例

legend:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html?highlight=legend#matplotlib.pyplot.legend

  • loc: 通过数字设置图例的位置
  • labels: 设置图例说明
  • ncol: 图例显示成多少列
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1, 5)
plt.subplot(131)
plt.plot(x, 2*x, label='2X')
plt.plot(x, 3*x, label='3X')
plt.plot(x, 4*x, label='4X')
plt.legend()

plt.subplot(132)
plt.plot(x, 2*x, label='2X')
plt.plot(x, 3*x, label='3X')
plt.plot(x, 4*x, label='4X')
plt.legend(loc=1)

plt.subplot(133)
plt.plot(x, 2*x, label='2X')
plt.plot(x, 3*x, label='3X')
plt.plot(x, 4*x, label='4X')
plt.legend(ncol = 2)
plt.show()

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure("grid")
x = np.arange(1, 5)

ax = fig.add_subplot(121)
plt.plot(x, 2*x, label='2X')
plt.plot(x, 3*x, label='3X')
plt.plot(x, 4*x, label='4X')
ax.legend()

ax = fig.add_subplot(122)
plt.plot(x, 2*x, label='2X')
plt.plot(x, 3*x, label='3X')
plt.plot(x, 4*x, label='4X')
ax.legend(labels=['A', 'B', 'C'])   # 通过labels该变图例说明
plt.show()

在这里插入图片描述

4、坐标轴范围

1、 通过plt.axis()设置:参数为一个有四个元素的列表,四个元素分别为[Xmin, Xmax, Ymin, Ymax]

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10, 11, 1)
plt.plot(x, x**2)
print(plt.axis())   # 打印默认的范围
plt.axis([-20, 20, 0, 200])
plt.show()

(-11.0, 11.0, -5.0, 105.0)

在这里插入图片描述

2、 通过xlim和ylim来设置:可以单独设置某一个坐标轴,也可以通过参数xmin,xmax,ymin,ymax来单独调整一个

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10, 11, 1)
plt.plot(x, x**2)
print(plt.axis())   # 打印默认的范围
print(plt.xlim())
plt.xlim(xmin=-15)  # 只调整x轴的最小值
plt.show()
(-11.0, 11.0, -5.0, 105.0)
(-11.0, 11.0)

在这里插入图片描述

5、设置坐标轴刻度

1、 通过locator_params()绘制:面向对象的方式是需要先获取坐标轴对象ax = plt.gca()

  • axis: 设置需要设置的坐标
  • nbins: 设置坐标轴的点的个数
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1, 11, 1)
plt.plot(x, x)
plt.locator_params('y', nbins=10)
plt.show()

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1, 11, 1)
plt.plot(x, x)

ax = plt.gca()
ax.locator_params('both', nbins=10)
plt.show()

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(0)
ax = fig.add_subplot(111)
x = np.arange(1, 11, 1)
plt.plot(x, x)
ax.locator_params('y', nbins=5)
plt.show()

在这里插入图片描述

2、 通过set_major_locator设置坐标轴间隔

  • locator: 首先创建一个MultipleLocator对象并存放在变量中,然后通过ax对象的xaxis和yaxis来设置
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(0)
ax = fig.add_subplot(111)
x = np.arange(1, 11, 1)
plt.plot(x, x)

#把x轴的刻度间隔设置为1,并存在变量里
x_major_locator = MultipleLocator(1)
#把y轴的刻度间隔设置为10,并存在变量里
y_major_locator = MultipleLocator(2)
#把x轴的主刻度设置为1的倍数
ax.xaxis.set_major_locator(x_major_locator)
#把y轴的主刻度设置为10的倍数
ax.yaxis.set_major_locator(y_major_locator)

plt.show()

在这里插入图片描述

6、横坐标为日期

  • 设置日期的格式
    date_format = mpl.dates.DateFormatter(’%Y.%m.%d’)
    ax.xaxis.set_major_formatter(date_format)
  • 根据格式自动调整很坐标的显示方式
    fig.autofmt_xdate()
import numpy as np
import matplotlib.pyplot as plt
import datetime
import matplotlib as mpl

start = datetime.datetime(2015,1,1)
end = datetime.datetime(2016,1,1)
delta = datetime.timedelta(days=1)

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

ax = plt.gca()
ax.plot_date(dates, y)
plt.show()

在这里插入图片描述

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

fig = plt.figure(0)
start = datetime.datetime(2015,1,1)
end = datetime.datetime(2016,1,1)
delte = datetime.timedelta(days=1)

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

ax = plt.gca()
ax.plot_date(dates, y)
# 设置日期的格式
date_format = mpl.dates.DateFormatter('%Y.%m.%d')
ax.xaxis.set_major_formatter(date_format)
# 根据格式自动调整很坐标的显示方式
fig.autofmt_xdate()
plt.show()

在这里插入图片描述

7、添加坐标轴

1、通过plt的方式绘制

  • 先绘制一条线
  • 通过plt.twinx()函数或者plt.twiny()绘制另一条坐标轴
  • 再绘制另一条线
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1, 20, 1)
y1 = x**2
y2 = np.log(x)

plt.plot(x, y1)
plt.twinx()
plt.plot(x, y2, 'r--')

plt.show()

在这里插入图片描述

2、通过面向对象的方式

  • 线绘制一条线
  • 通过ax对象添加twinx或者twiny添加另一条坐标轴
  • 绘制另一条线
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1, 20, 1)
y1 = x**2
y2 = np.log(x)

fig = plt.figure(0)
ax1 = fig.add_subplot(111)

ax1.plot(x, y1)
ax1.set_ylabel("Y1")

ax2 = ax1.twinx()
ax2.plot(x, y2, 'r--')
ax2.set_ylabel('Y2')

plt.show()

在这里插入图片描述

8、添加注释

通过annotate来添加

  • text:str,用来定义显示的注释的字符串
  • xy: 需要注释的点的坐标
  • xytext: 文字显示的坐标
  • arrowprops:dict类型,定义箭头的属性
  • facecolor: 定义颜色
  • headlength: 定义箭头三角形的高度,也可以通过frac=0.3这种形式来设置头部三角形占的比例,不过这种方式后面不在支持
  • headwidth: 定义三角形的宽度
  • width: 定义整体的宽度
import numpy as np
import matplotlib.pyplot as plt

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

plt.plot(x, y)
plt.annotate("this is the bottom", xy=(0,1), xytext=(0, 20), arrowprops=dict(facecolor='r', headlength=10, headwidth=20, width=10))

plt.show()

在这里插入图片描述

9、添加纯文字

plt.text():

  • x, y, s:坐标和字符串
  • family:设置字体, ‘serif’,‘sans-serif’,‘cursive’,‘fantasy’,‘monospace’
  • stytle: 可以设置斜体
  • weight: 设置字体的宽度
  • bbox: 设置底层框,dict类型,通过不同参数设置底框属性
import numpy as np
import matplotlib.pyplot as plt

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

plt.plot(x, y)
plt.text(x = 0, y = 20, s ="y=x**2", family='monospace')
plt.text(x = 0, y = 30, s ="y=x**2", family='monospace', color='r', style='italic', weight='light', bbox=dict(facecolor='g', alpha=0.5))

plt.show()

在这里插入图片描述

10、Tex数学公式

通过Tex的公式来显示公式

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim([1, 7])
plt.ylim([1, 5])

ax.text(2, 4, r"$ y=2*x $")
ax.text(4, 4, r"$ \sin(0) = \cos(\frac{\pi}{2}) $", size=22)
plt.show()

在这里插入图片描述

11、样式美化

通过plt.style.use()来设置:常用的样式可以通过plt.style.available()查询

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(100)
y = np.random.randn(100)
plt.scatter(x, y)

plt.show()

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt

plt.style.use('seaborn')

x = np.random.randn(100)
y = np.random.randn(100)

plt.scatter(x, y)
plt.show()

在这里插入图片描述

PS:边学边做的笔记,没来得及检查.如果发现错误或者有漏掉的常用操作还请提出,及时修正,避免不必要的误导浪费时间,可评论或邮箱:wtzhu_13@163.com

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值