0


Python基础(十二) | 还不会python绘图?两万字博文教你Matplotlib库(超详细总结)

⭐本专栏旨在对Python的基础语法进行详解,精炼地总结语法中的重点,详解难点,面向零基础及入门的学习者,通过专栏的学习可以熟练掌握python编程,同时为后续的数据分析,机器学习及深度学习的代码能力打下坚实的基础。

🔥本文已收录于Python基础系列专栏: Python基础系列教程 欢迎订阅,持续更新。

image-20221007090551954

image-20221007090608537

文章目录

13.0 环境配置

【1】 要不要plt.show()

  • ipython中可用魔术方法 %matplotlib inline
  • pycharm 中必须使用plt.show()
  1. %matplotlib inline # 配置,可以再ipython中生成就显示,而不需要多余plt.show来完成。import matplotlib.pyplot as plt
  2. plt.style.use("seaborn-whitegrid")# 用来永久地改变风格,与下文with临时改变进行对比
  1. x =[1,2,3,4]
  2. y =[1,4,9,16]
  3. plt.plot(x, y)
  4. plt.ylabel("squares")# plt.show()
  1. Text(0, 0.5, 'squares')

png

【2】设置样式

  1. plt.style.available[:5]
  1. ['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight']

临时地改变风格,采用with这个上下文管理器。

  1. with plt.style.context("seaborn-white"):
  2. plt.plot(x, y)

png

【3】将图像保存为文件

  1. import numpy as np
  2. x = np.linspace(0,10,100)
  3. plt.plot(x, np.exp(x))
  4. plt.savefig("my_figure.png")

png

13.1 Matplotlib库

image-20221007090619966

13.1.1 折线图

  1. %matplotlib inline
  2. import matplotlib.pyplot as plt
  3. plt.style.use("seaborn-whitegrid")import numpy as np
  1. x = np.linspace(0,2*np.pi,100)
  2. plt.plot(x, np.sin(x))
  1. [<matplotlib.lines.Line2D at 0x18846169780>]

png

  • 绘制多条曲线
  1. x = np.linspace(0,2*np.pi,100)
  2. plt.plot(x, np.cos(x))
  3. plt.plot(x, np.sin(x))
  1. [<matplotlib.lines.Line2D at 0x1884615f9e8>]

png

【1】调整线条颜色和风格

  • 调整线条颜色
  1. offsets = np.linspace(0, np.pi,5)
  2. colors =["blue","g","r","yellow","pink"]for offset, color inzip(offsets, colors):
  3. plt.plot(x, np.sin(x-offset), color=color)# color可缩写为c

png

  • 调整线条风格
  1. x = np.linspace(0,10,11)
  2. offsets =list(range(8))
  3. linestyles =["solid","dashed","dashdot","dotted","-","--","-.",":"]for offset, linestyle inzip(offsets, linestyles):
  4. plt.plot(x, x+offset, linestyle=linestyle)# linestyle可简写为ls

png

  • 调整线宽
  1. x = np.linspace(0,10,11)
  2. offsets =list(range(0,12,3))
  3. linewidths =(i*2for i inrange(1,5))for offset, linewidth inzip(offsets, linewidths):
  4. plt.plot(x, x+offset, linewidth=linewidth)# linewidth可简写为lw

png

  • 调整数据点标记
marker设置坐标点
  1. x = np.linspace(0,10,11)
  2. offsets =list(range(0,12,3))
  3. markers =["*","+","o","s"]for offset, marker inzip(offsets, markers):
  4. plt.plot(x, x+offset, marker=marker)

png

markersize 设置坐标点大小
  1. x = np.linspace(0,10,11)
  2. offsets =list(range(0,12,3))
  3. markers =["*","+","o","s"]for offset, marker inzip(offsets, markers):
  4. plt.plot(x, x+offset, marker=marker, markersize=10)# markersize可简写为ms

png

颜色跟风格设置的简写 color_linestyles = [“g-”, “b–”, “k-.”, “r:”]
  1. x = np.linspace(0,10,11)
  2. offsets =list(range(0,8,2))
  3. color_linestyles =["g-","b--","k-.","r:"]for offset, color_linestyle inzip(offsets, color_linestyles):
  4. plt.plot(x, x+offset, color_linestyle)

png

颜色_风格_线性 设置的简写 color_marker_linestyles = [“g*-”, “b±-”, “ko-.”, “rs:”]
  1. x = np.linspace(0,10,11)
  2. offsets =list(range(0,8,2))
  3. color_marker_linestyles =["g*-","b+--","ko-.","rs:"]for offset, color_marker_linestyle inzip(offsets, color_marker_linestyles):
  4. plt.plot(x, x+offset, color_marker_linestyle)


png

其他用法及颜色缩写、数据点标记缩写等请查看官方文档,如下:

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot

【2】调整坐标轴

  • xlim, ylim # 限制x,y轴
  1. x = np.linspace(0,2*np.pi,100)
  2. plt.plot(x, np.sin(x))
  3. plt.xlim(-1,7)
  4. plt.ylim(-1.5,1.5)
  1. (-1.5, 1.5)

png

  • axis
  1. x = np.linspace(0,2*np.pi,100)
  2. plt.plot(x, np.sin(x))
  3. plt.axis([-2,8,-2,2])
  1. [-2, 8, -2, 2]

png

tight 会紧凑一点

  1. x = np.linspace(0,2*np.pi,100)
  2. plt.plot(x, np.sin(x))
  3. plt.axis("tight")
  1. (0.0, 6.283185307179586, -0.9998741276738751, 0.9998741276738751)

png

equal 会松一点

  1. x = np.linspace(0,2*np.pi,100)
  2. plt.plot(x, np.sin(x))
  3. plt.axis("equal")
  1. (0.0, 7.0, -1.0, 1.0)

png

  1. ?plt.axis # 可以查询其中的功能
  1. Object `plt.axis # 可以查询其中的功能` not found.
  • 对数坐标
  1. x = np.logspace(0,5,100)
  2. plt.plot(x, np.log(x))
  3. plt.xscale("log")

png

  • 调整坐标轴刻度

plt.xticks(np.arange(0, 12, step=1))

  1. x = np.linspace(0,10,100)
  2. plt.plot(x, x**2)
  3. plt.xticks(np.arange(0,12, step=1))
  1. ([<matplotlib.axis.XTick at 0x18846412828>,
  2. <matplotlib.axis.XTick at 0x18847665898>,
  3. <matplotlib.axis.XTick at 0x18847665630>,
  4. <matplotlib.axis.XTick at 0x18847498978>,
  5. <matplotlib.axis.XTick at 0x18847498390>,
  6. <matplotlib.axis.XTick at 0x18847497d68>,
  7. <matplotlib.axis.XTick at 0x18847497748>,
  8. <matplotlib.axis.XTick at 0x18847497438>,
  9. <matplotlib.axis.XTick at 0x1884745f438>,
  10. <matplotlib.axis.XTick at 0x1884745fd68>,
  11. <matplotlib.axis.XTick at 0x18845fcf4a8>,
  12. <matplotlib.axis.XTick at 0x18845fcf320>],
  13. <a list of 12 Text xticklabel objects>)

png

  1. x = np.linspace(0,10,100)
  2. plt.plot(x, x**2)
  3. plt.xticks(np.arange(0,12, step=1), fontsize=15)
  4. plt.yticks(np.arange(0,110, step=10))
  1. ([<matplotlib.axis.YTick at 0x188474f0860>,
  2. <matplotlib.axis.YTick at 0x188474f0518>,
  3. <matplotlib.axis.YTick at 0x18847505a58>,
  4. <matplotlib.axis.YTick at 0x188460caac8>,
  5. <matplotlib.axis.YTick at 0x1884615c940>,
  6. <matplotlib.axis.YTick at 0x1884615cdd8>,
  7. <matplotlib.axis.YTick at 0x1884615c470>,
  8. <matplotlib.axis.YTick at 0x1884620c390>,
  9. <matplotlib.axis.YTick at 0x1884611f898>,
  10. <matplotlib.axis.YTick at 0x188461197f0>,
  11. <matplotlib.axis.YTick at 0x18846083f98>],
  12. <a list of 11 Text yticklabel objects>)

png

  • 调整刻度样式

plt.tick_params(axis=“both”, labelsize=15)

  1. x = np.linspace(0,10,100)
  2. plt.plot(x, x**2)
  3. plt.tick_params(axis="both", labelsize=15)

png

【3】设置图形标签

  1. x = np.linspace(0,2*np.pi,100)
  2. plt.plot(x, np.sin(x))
  3. plt.title("A Sine Curve", fontsize=20)
  4. plt.xlabel("x", fontsize=15)
  5. plt.ylabel("sin(x)", fontsize=15)
  1. Text(0, 0.5, 'sin(x)')

png

【4】设置图例

  • 默认
  1. x = np.linspace(0,2*np.pi,100)
  2. plt.plot(x, np.sin(x),"b-", label="Sin")
  3. plt.plot(x, np.cos(x),"r--", label="Cos")
  4. plt.legend()
  1. <matplotlib.legend.Legend at 0x1884749f908>

png

  • 修饰图例
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. x = np.linspace(0,2*np.pi,100)
  4. plt.plot(x, np.sin(x),"b-", label="Sin")
  5. plt.plot(x, np.cos(x),"r--", label="Cos")
  6. plt.ylim(-1.5,2)
  7. plt.legend(loc="upper center", frameon=True, fontsize=15)# frameon=True增加图例的边框
  1. <matplotlib.legend.Legend at 0x19126b53b80>

png

【5】添加文字和箭头

  • 添加文字
  1. x = np.linspace(0,2*np.pi,100)
  2. plt.plot(x, np.sin(x),"b-")
  3. plt.text(3.5,0.5,"y=sin(x)", fontsize=15)# 前两个为文字的坐标,后面是内容和字号
  1. Text(3.5, 0.5, 'y=sin(x)')

png

  • 添加箭头
  1. x = np.linspace(0,2*np.pi,100)
  2. plt.plot(x, np.sin(x),"b-")
  3. plt.annotate('local min', xy=(1.5*np.pi,-1), xytext=(4.5,0),
  4. arrowprops=dict(facecolor='black', shrink=0.1),)
  1. Text(4.5, 0, 'local min')

png

13.1.2 散点图

【1】简单散点图

  1. x = np.linspace(0,2*np.pi,20)
  2. plt.scatter(x, np.sin(x), marker="o", s=30, c="r")# s 大小 c 颜色
  1. <matplotlib.collections.PathCollection at 0x188461eb4a8>

png

【2】颜色配置

  1. x = np.linspace(0,10,100)
  2. y = x**2
  3. plt.scatter(x, y, c=y, cmap="inferno")# c随着y的值变化在cmap中进行映射
  4. plt.colorbar()# 输出颜色条
  1. <matplotlib.colorbar.Colorbar at 0x18848d392e8>

png

颜色配置参考官方文档

https://matplotlib.org/examples/color/colormaps_reference.html

【3】根据数据控制点的大小

  1. x, y, colors, size =(np.random.rand(100)for i inrange(4))
  2. plt.scatter(x, y, c=colors, s=1000*size, cmap="viridis")
  1. <matplotlib.collections.PathCollection at 0x18847b48748>

png

【4】透明度

  1. x, y, colors, size =(np.random.rand(100)for i inrange(4))
  2. plt.scatter(x, y, c=colors, s=1000*size, cmap="viridis", alpha=0.3)
  3. plt.colorbar()
  1. <matplotlib.colorbar.Colorbar at 0x18848f2be10>

png

【例】随机漫步

  1. from random import choice
  2. classRandomWalk():"""一个生产随机漫步的类"""def__init__(self, num_points=5000):
  3. self.num_points = num_points
  4. self.x_values =[0]
  5. self.y_values =[0]deffill_walk(self):whilelen(self.x_values)< self.num_points:
  6. x_direction = choice([1,-1])
  7. x_distance = choice([0,1,2,3,4])
  8. x_step = x_direction * x_distance
  9. y_direction = choice([1,-1])
  10. y_distance = choice([0,1,2,3,4])
  11. y_step = y_direction * y_distance
  12. if x_step ==0or y_step ==0:continue
  13. next_x = self.x_values[-1]+ x_step
  14. next_y = self.y_values[-1]+ y_step
  15. self.x_values.append(next_x)
  16. self.y_values.append(next_y)
  1. rw = RandomWalk(10000)
  2. rw.fill_walk()
  3. point_numbers =list(range(rw.num_points))
  4. plt.figure(figsize=(12,6))# 设置画布大小
  5. plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap="inferno", s=1)
  6. plt.colorbar()
  7. plt.scatter(0,0, c="green", s=100)
  8. plt.scatter(rw.x_values[-1], rw.y_values[-1], c="red", s=100)
  9. plt.xticks([])
  10. plt.yticks([])
  1. ([], <a list of 0 Text yticklabel objects>)


png

13.1.3 柱形图

【1】简单柱形图

  1. x = np.arange(1,6)
  2. plt.bar(x,2*x, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')
  3. plt.tick_params(axis="both", labelsize=13)

png

  1. x = np.arange(1,6)
  2. plt.bar(x,2*x, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')
  3. plt.xticks(x,('G1','G2','G3','G4','G5'))
  4. plt.tick_params(axis="both", labelsize=13)

png

  1. x =('G1','G2','G3','G4','G5')
  2. y =2* np.arange(1,6)
  3. plt.bar(x, y, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')
  4. plt.tick_params(axis="both", labelsize=13)

png

  1. x =["G"+str(i)for i inrange(5)]
  2. y =1/(1+np.exp(-np.arange(5)))
  3. colors =['red','yellow','blue','green','gray']
  4. plt.bar(x, y, align="center", width=0.5, alpha=0.5, color=colors)
  5. plt.tick_params(axis="both", labelsize=13)

png

【2】累加柱形图

  1. x = np.arange(5)
  2. y1 = np.random.randint(20,30, size=5)
  3. y2 = np.random.randint(20,30, size=5)
  4. plt.bar(x, y1, width=0.5, label="man")
  5. plt.bar(x, y2, width=0.5, bottom=y1, label="women")
  6. plt.legend()
  1. <matplotlib.legend.Legend at 0x2052db25cc0>

png

【3】并列柱形图

  1. x = np.arange(15)
  2. y1 = x+1
  3. y2 = y1+np.random.random(15)
  4. plt.bar(x, y1, width=0.3, label="man")
  5. plt.bar(x+0.3, y2, width=0.3, label="women")
  6. plt.legend()
  1. <matplotlib.legend.Legend at 0x2052daf35f8>

png

【4】横向柱形图barh

  1. x =['G1','G2','G3','G4','G5']
  2. y =2* np.arange(1,6)
  3. plt.barh(x, y, align="center", height=0.5, alpha=0.8, color="blue", edgecolor="red")# 注意这里将bar改为barh,宽度用height设置
  4. plt.tick_params(axis="both", labelsize=13)

png

13.1.4 多子图

【1】简单多子图

  1. deff(t):return np.exp(-t)* np.cos(2*np.pi*t)
  2. t1 = np.arange(0.0,5.0,0.1)
  3. t2 = np.arange(0.0,5.0,0.02)
  4. plt.subplot(211)
  5. plt.plot(t1, f(t1),"bo-", markerfacecolor="r", markersize=5)
  6. plt.title("A tale of 2 subplots")
  7. plt.ylabel("Damped oscillation")
  8. plt.subplot(212)
  9. plt.plot(t2, np.cos(2*np.pi*t2),"r--")
  10. plt.xlabel("time (s)")
  11. plt.ylabel("Undamped")
  1. Text(0, 0.5, 'Undamped')

png

【2】多行多列子图

  1. x = np.random.random(10)
  2. y = np.random.random(10)
  3. plt.subplots_adjust(hspace=0.5, wspace=0.3)
  4. plt.subplot(321)
  5. plt.scatter(x, y, s=80, c="b", marker=">")
  6. plt.subplot(322)
  7. plt.scatter(x, y, s=80, c="g", marker="*")
  8. plt.subplot(323)
  9. plt.scatter(x, y, s=80, c="r", marker="s")
  10. plt.subplot(324)
  11. plt.scatter(x, y, s=80, c="c", marker="p")
  12. plt.subplot(325)
  13. plt.scatter(x, y, s=80, c="m", marker="+")
  14. plt.subplot(326)
  15. plt.scatter(x, y, s=80, c="y", marker="H")
  1. <matplotlib.collections.PathCollection at 0x2052d9f63c8>

png

【3】不规则多子图

  1. deff(x):return np.exp(-x)* np.cos(2*np.pi*x)
  2. x = np.arange(0.0,3.0,0.01)
  3. grid = plt.GridSpec(2,3, wspace=0.4, hspace=0.3)# 两行三列的网格
  4. plt.subplot(grid[0,0])# 第一行第一列位置
  5. plt.plot(x, f(x))
  6. plt.subplot(grid[0,1:])# 第一行后两列的位置
  7. plt.plot(x, f(x),"r--", lw=2)
  8. plt.subplot(grid[1,:])# 第二行所有位置
  9. plt.plot(x, f(x),"g-.", lw=3)
  1. [<matplotlib.lines.Line2D at 0x2052d6fae80>]

png

13.1.5 直方图

【1】普通频次直方图

  1. mu, sigma =100,15
  2. x = mu + sigma * np.random.randn(10000)
  3. plt.hist(x, bins=50, facecolor='g', alpha=0.75)
  1. (array([ 1., 0., 0., 5., 3., 5., 1., 10., 15., 19., 37.,
  2. 55., 81., 94., 125., 164., 216., 258., 320., 342., 401., 474.,
  3. 483., 590., 553., 551., 611., 567., 515., 558., 470., 457., 402.,
  4. 347., 261., 227., 206., 153., 128., 93., 79., 41., 22., 17.,
  5. 21., 9., 2., 8., 1., 2.]),
  6. array([ 40.58148736, 42.82962161, 45.07775586, 47.32589011,
  7. 49.57402436, 51.82215862, 54.07029287, 56.31842712,
  8. 58.56656137, 60.81469562, 63.06282988, 65.31096413,
  9. 67.55909838, 69.80723263, 72.05536689, 74.30350114,
  10. 76.55163539, 78.79976964, 81.04790389, 83.29603815,
  11. 85.5441724 , 87.79230665, 90.0404409 , 92.28857515,
  12. 94.53670941, 96.78484366, 99.03297791, 101.28111216,
  13. 103.52924641, 105.77738067, 108.02551492, 110.27364917,
  14. 112.52178342, 114.76991767, 117.01805193, 119.26618618,
  15. 121.51432043, 123.76245468, 126.01058893, 128.25872319,
  16. 130.50685744, 132.75499169, 135.00312594, 137.25126019,
  17. 139.49939445, 141.7475287 , 143.99566295, 146.2437972 ,
  18. 148.49193145, 150.74006571, 152.98819996]),
  19. <a list of 50 Patch objects>)

png

【2】概率密度

  1. mu, sigma =100,15
  2. x = mu + sigma * np.random.randn(10000)
  3. plt.hist(x,50, density=True, color="r")# 概率密度图
  4. plt.xlabel('Smarts')
  5. plt.ylabel('Probability')
  6. plt.title('Histogram of IQ')
  7. plt.text(60,.025,r'$\mu=100,\ \sigma=15$')
  8. plt.xlim(40,160)
  9. plt.ylim(0,0.03)
  1. (0, 0.03)

png

  1. mu, sigma =100,15
  2. x = mu + sigma * np.random.randn(10000)
  3. plt.hist(x, bins=50, density=True, color="r", histtype='step')#不填充,只获得边缘
  4. plt.xlabel('Smarts')
  5. plt.ylabel('Probability')
  6. plt.title('Histogram of IQ')
  7. plt.text(60,.025,r'$\mu=100,\ \sigma=15$')
  8. plt.xlim(40,160)
  9. plt.ylim(0,0.03)
  1. (0, 0.03)

png

  1. from scipy.stats import norm
  2. mu, sigma =100,15# 想获得真正高斯分布的概率密度图
  3. x = mu + sigma * np.random.randn(10000)# 先获得bins,即分配的区间
  4. _, bins, __ = plt.hist(x,50, density=True)
  5. y = norm.pdf(bins, mu, sigma)# 通过norm模块计算符合的概率密度
  6. plt.plot(bins, y,'r--', lw=3)
  7. plt.xlabel('Smarts')
  8. plt.ylabel('Probability')
  9. plt.title('Histogram of IQ')
  10. plt.text(60,.025,r'$\mu=100,\ \sigma=15$')
  11. plt.xlim(40,160)
  12. plt.ylim(0,0.03)
  1. (0, 0.03)

png

【3】累计概率分布

  1. mu, sigma =100,15
  2. x = mu + sigma * np.random.randn(10000)
  3. plt.hist(x,50, density=True, cumulative=True, color="r")# 将累计cumulative设置为true即可
  4. plt.xlabel('Smarts')
  5. plt.ylabel('Cum_Probability')
  6. plt.title('Histogram of IQ')
  7. plt.text(60,0.8,r'$\mu=100,\ \sigma=15$')
  8. plt.xlim(50,165)
  9. plt.ylim(0,1.1)
  1. (0, 1.1)

png

【例】模拟投两个骰子

  1. classDie():"模拟一个骰子的类"def__init__(self, num_sides=6):
  2. self.num_sides = num_sides
  3. defroll(self):return np.random.randint(1, self.num_sides+1)
  • 重复投一个骰子
  1. die = Die()
  2. results =[]for i inrange(60000):
  3. result = die.roll()
  4. results.append(result)
  5. plt.hist(results, bins=6,range=(0.75,6.75), align="mid", width=0.5)
  6. plt.xlim(0,7)
  1. (0, 7)

png

  • 重复投两个骰子
  1. die1 = Die()
  2. die2 = Die()
  3. results =[]for i inrange(60000):
  4. result = die1.roll()+die2.roll()
  5. results.append(result)
  6. plt.hist(results, bins=11,range=(1.75,12.75), align="mid", width=0.5)
  7. plt.xlim(1,13)
  8. plt.xticks(np.arange(1,14))
  1. ([<matplotlib.axis.XTick at 0x2052fae23c8>,
  2. <matplotlib.axis.XTick at 0x2052ff1fa20>,
  3. <matplotlib.axis.XTick at 0x2052fb493c8>,
  4. <matplotlib.axis.XTick at 0x2052e9b5a20>,
  5. <matplotlib.axis.XTick at 0x2052e9b5e80>,
  6. <matplotlib.axis.XTick at 0x2052e9b5978>,
  7. <matplotlib.axis.XTick at 0x2052e9cc668>,
  8. <matplotlib.axis.XTick at 0x2052e9ccba8>,
  9. <matplotlib.axis.XTick at 0x2052e9ccdd8>,
  10. <matplotlib.axis.XTick at 0x2052fac5668>,
  11. <matplotlib.axis.XTick at 0x2052fac5ba8>,
  12. <matplotlib.axis.XTick at 0x2052fac5dd8>,
  13. <matplotlib.axis.XTick at 0x2052fad9668>],
  14. <a list of 13 Text xticklabel objects>)

png

13.1.6 误差图

【1】基本误差图

  1. x = np.linspace(0,10,50)
  2. dy =0.5# 每个点的y值误差设置为0.5
  3. y = np.sin(x)+ dy*np.random.randn(50)
  4. plt.errorbar(x, y , yerr=dy, fmt="+b")
  1. <ErrorbarContainer object of 3 artists>

png

【2】柱形图误差图

  1. menMeans =(20,35,30,35,27)
  2. womenMeans =(25,32,34,20,25)
  3. menStd =(2,3,4,1,2)
  4. womenStd =(3,5,2,3,3)
  5. ind =['G1','G2','G3','G4','G5']
  6. width =0.35
  7. p1 = plt.bar(ind, menMeans, width=width, label="Men", yerr=menStd)
  8. p2 = plt.bar(ind, womenMeans, width=width, bottom=menMeans, label="Men", yerr=womenStd)
  9. plt.ylabel('Scores')
  10. plt.title('Scores by group and gender')
  11. plt.yticks(np.arange(0,81,10))
  12. plt.legend()
  1. <matplotlib.legend.Legend at 0x20531035630>

png

13.1.7 面向对象的风格简介

【例1】 普通图

  1. x = np.linspace(0,5,10)
  2. y = x **2
  3. fig = plt.figure(figsize=(8,4), dpi=80)# 图像
  4. axes = fig.add_axes([0.1,0.1,0.8,0.8])# left, bottom, width, height (range 0 to 1)
  5. axes.plot(x, y,'r')
  6. axes.set_xlabel('x')
  7. axes.set_ylabel('y')
  8. axes.set_title('title')
  1. Text(0.5, 1.0, 'title')

png

【2】画中画

  1. x = np.linspace(0,5,10)
  2. y = x **2
  3. fig = plt.figure()
  4. ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
  5. ax2 = fig.add_axes([0.2,0.5,0.4,0.3])
  6. ax1.plot(x, y,'r')
  7. ax1.set_xlabel('x')
  8. ax1.set_ylabel('y')
  9. ax1.set_title('title')
  10. ax2.plot(y, x,'g')
  11. ax2.set_xlabel('y')
  12. ax2.set_ylabel('x')
  13. ax2.set_title('insert title')
  1. Text(0.5, 1.0, 'insert title')

png

【3】 多子图

  1. deff(t):return np.exp(-t)* np.cos(2*np.pi*t)
  2. t1 = np.arange(0.0,3.0,0.01)
  3. fig= plt.figure()
  4. fig.subplots_adjust(hspace=0.4, wspace=0.4)
  5. ax1 = plt.subplot(2,2,1)
  6. ax1.plot(t1, f(t1))
  7. ax1.set_title("Upper left")
  8. ax2 = plt.subplot(2,2,2)
  9. ax2.plot(t1, f(t1))
  10. ax2.set_title("Upper right")
  11. ax3 = plt.subplot(2,1,2)
  12. ax3.plot(t1, f(t1))
  13. ax3.set_title("Lower")
  1. Text(0.5, 1.0, 'Lower')

png

13.1.8 三维图形简介

【1】三维数据点与线

  1. from mpl_toolkits import mplot3d # 注意要导入mplot3d
  2. ax = plt.axes(projection="3d")
  3. zline = np.linspace(0,15,1000)
  4. xline = np.sin(zline)
  5. yline = np.cos(zline)
  6. ax.plot3D(xline, yline ,zline)# 线的绘制
  7. zdata =15*np.random.random(100)
  8. xdata = np.sin(zdata)
  9. ydata = np.cos(zdata)
  10. ax.scatter3D(xdata, ydata ,zdata, c=zdata, cmap="spring")# 点的绘制
  1. <mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x2052fd1e5f8>

png

【2】三维数据曲面图

  1. deff(x, y):return np.sin(np.sqrt(x**2+ y**2))
  2. x = np.linspace(-6,6,30)
  3. y = np.linspace(-6,6,30)
  4. X, Y = np.meshgrid(x, y)# 网格化
  5. Z = f(X, Y)
  6. ax = plt.axes(projection="3d")
  7. ax.plot_surface(X, Y, Z, cmap="viridis")# 设置颜色映射
  1. <mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x20531baa5c0>

png

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from mpl_toolkits import mplot3d
  4. t = np.linspace(0,2*np.pi,1000)
  5. X = np.sin(t)
  6. Y = np.cos(t)
  7. Z = np.arange(t.size)[:, np.newaxis]
  8. ax = plt.axes(projection="3d")
  9. ax.plot_surface(X, Y, Z, cmap="viridis")
  1. <mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x1c540cf1cc0>

png

13.2 Seaborn库-文艺青年的最爱

【1】Seaborn 与 Matplotlib

Seaborn 是一个基于 matplotlib 且数据结构与 pandas 统一的统计图制作库

  1. x = np.linspace(0,10,500)
  2. y = np.cumsum(np.random.randn(500,6), axis=0)with plt.style.context("classic"):
  3. plt.plot(x, y)
  4. plt.legend("ABCDEF", ncol=2, loc="upper left")

png

  1. import seaborn as sns
  2. x = np.linspace(0,10,500)
  3. y = np.cumsum(np.random.randn(500,6), axis=0)
  4. sns.set()# 改变了格式
  5. plt.figure(figsize=(10,6))
  6. plt.plot(x, y)
  7. plt.legend("ABCDEF", ncol=2, loc="upper left")
  1. <matplotlib.legend.Legend at 0x20533d825f8>

png

【2】柱形图的对比

  1. x =['G1','G2','G3','G4','G5']
  2. y =2* np.arange(1,6)
  3. plt.figure(figsize=(8,4))
  4. plt.barh(x, y, align="center", height=0.5, alpha=0.8, color="blue")
  5. plt.tick_params(axis="both", labelsize=13)

png

  1. import seaborn as sns
  2. plt.figure(figsize=(8,4))
  3. x =['G5','G4','G3','G2','G1']
  4. y =2* np.arange(5,0,-1)#sns.barplot(y, x)
  5. sns.barplot(y, x, linewidth=5)
  1. <matplotlib.axes._subplots.AxesSubplot at 0x20533e92048>

png

  1. sns.barplot?

【3】以鸢尾花数据集为例

  1. iris = sns.load_dataset("iris")
  1. iris.head()

sepal_lengthsepal_widthpetal_lengthpetal_widthspecies05.13.51.40.2setosa14.93.01.40.2setosa24.73.21.30.2setosa34.63.11.50.2setosa45.03.61.40.2setosa

  1. sns.pairplot(data=iris, hue="species")
  1. <seaborn.axisgrid.PairGrid at 0x205340655f8>

png

13.3 Pandas 中的绘图函数概览

  1. import pandas as pd

【1】线形图

  1. df = pd.DataFrame(np.random.randn(1000,4).cumsum(axis=0),
  2. columns=list("ABCD"),
  3. index=np.arange(1000))
  4. df.head()

ABCD0-1.3114430.970917-1.635011-0.2047791-1.6185020.810056-1.1192461.2396892-3.5587871.431716-0.8162011.1556113-5.377557-0.3127440.6509220.3521764-3.9170451.1810971.5724060.965921

  1. df.plot()
  1. <matplotlib.axes._subplots.AxesSubplot at 0x20534763f28>

png

  1. df = pd.DataFrame()
  2. df.plot?

【2】柱形图

  1. df2 = pd.DataFrame(np.random.rand(10,4), columns=['a','b','c','d'])
  2. df2

abcd00.5876000.0987360.4447570.87747510.5800620.4515190.2123180.42967320.4153070.7840830.8912050.75628730.1900530.3509870.6625490.72919340.4856020.1099740.8915540.47349250.3318840.1289570.2043030.36342060.9627500.4312260.9176820.97271370.4834100.4865920.4392350.87521080.0543370.9858120.4690160.89471290.7309050.2371660.0431950.600445

  • 多组数据竖图
  1. df2.plot.bar()
  1. <matplotlib.axes._subplots.AxesSubplot at 0x20534f1cb00>

png

  • 多组数据累加竖图
  1. df2.plot.bar(stacked=True)# 累加的柱形图
  1. <matplotlib.axes._subplots.AxesSubplot at 0x20534f22208>

png

  • 多组数据累加横图
  1. df2.plot.barh(stacked=True)# 变为barh
  1. <matplotlib.axes._subplots.AxesSubplot at 0x2053509d048>

png

【3】直方图和密度图

  1. df4 = pd.DataFrame({"A": np.random.randn(1000)-3,"B": np.random.randn(1000),"C": np.random.randn(1000)+3})
  2. df4.head()

ABC0-4.2504241.0432681.3561061-2.393362-0.8916203.7879062-4.4112250.4363811.2427493-3.465659-0.8459661.5403474-3.6068501.6434043.689431

  • 普通直方图
  1. df4.plot.hist(bins=50)
  1. <matplotlib.axes._subplots.AxesSubplot at 0x20538383b38>

png

  • 累加直方图
  1. df4['A'].plot.hist(cumulative=True)
  1. <matplotlib.axes._subplots.AxesSubplot at 0x2053533bbe0>

png

  • 概率密度图
  1. df4['A'].plot(kind="kde")
  1. <matplotlib.axes._subplots.AxesSubplot at 0x205352c4e48>

png

  • 差分
  1. df = pd.DataFrame(np.random.randn(1000,4).cumsum(axis=0),
  2. columns=list("ABCD"),
  3. index=np.arange(1000))
  4. df.head()

ABCD0-0.277843-0.310656-0.782999-0.04903210.644248-0.505115-0.3638420.3991162-0.614141-1.227740-0.787415-0.1174853-0.055964-2.376631-0.814320-0.71617940.058613-2.355537-2.1742910.351918

  1. df.diff().hist(bins=50, color="r")
  1. array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000002053942A6A0>,
  2. <matplotlib.axes._subplots.AxesSubplot object at 0x000002053957FE48>],
  3. [<matplotlib.axes._subplots.AxesSubplot object at 0x00000205395A4780>,
  4. <matplotlib.axes._subplots.AxesSubplot object at 0x00000205395D4128>]],
  5. dtype=object)

png

  1. df = pd.DataFrame()
  2. df.hist?

【4】散点图

  1. housing = pd.read_csv("housing.csv")
  2. housing.head()

longitudelatitudehousing_median_agetotal_roomstotal_bedroomspopulationhouseholdsmedian_incomemedian_house_valueocean_proximity0-122.2337.8841.0880.0129.0322.0126.08.3252452600.0NEAR BAY1-122.2237.8621.07099.01106.02401.01138.08.3014358500.0NEAR BAY2-122.2437.8552.01467.0190.0496.0177.07.2574352100.0NEAR BAY3-122.2537.8552.01274.0235.0558.0219.05.6431341300.0NEAR BAY4-122.2537.8552.01627.0280.0565.0259.03.8462342200.0NEAR BAY

  1. """基于地理数据的人口、房价可视化"""# 圆的半价大小代表每个区域人口数量(s),颜色代表价格(c),用预定义的jet表进行可视化with sns.axes_style("white"):
  2. housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.6,
  3. s=housing["population"]/100, label="population",
  4. c="median_house_value", cmap="jet", colorbar=True, figsize=(12,8))
  5. plt.legend()
  6. plt.axis([-125,-113.5,32,43])
  1. [-125, -113.5, 32, 43]

png

  1. housing.plot(kind="scatter", x="median_income", y="median_house_value", alpha=0.8)
  1. 'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.
  2. <matplotlib.axes._subplots.AxesSubplot at 0x2053a45a9b0>

png

【5】多子图

  1. df = pd.DataFrame(np.random.randn(1000,4).cumsum(axis=0),
  2. columns=list("ABCD"),
  3. index=np.arange(1000))
  4. df.head()

ABCD0-0.1345100.364371-0.831193-0.79690310.1301021.003402-0.622822-1.64077120.0668730.1261740.180913-2.9286433-1.686890-0.0507400.312582-2.37945540.655660-0.390920-1.144121-2.625653

  • 默认情形
  1. df.plot(subplots=True, figsize=(6,16))
  1. array([<matplotlib.axes._subplots.AxesSubplot object at 0x0000020539BF46D8>,
  2. <matplotlib.axes._subplots.AxesSubplot object at 0x0000020539C11898>,
  3. <matplotlib.axes._subplots.AxesSubplot object at 0x0000020539C3D0B8>,
  4. <matplotlib.axes._subplots.AxesSubplot object at 0x0000020539C60908>],
  5. dtype=object)

png

  • 设定图形安排
  1. df.plot(subplots=True, layout=(2,2), figsize=(16,6), sharex=False)
  1. array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000002053D9C2898>,
  2. <matplotlib.axes._subplots.AxesSubplot object at 0x000002053D9F5668>],
  3. [<matplotlib.axes._subplots.AxesSubplot object at 0x000002053D68BF98>,
  4. <matplotlib.axes._subplots.AxesSubplot object at 0x000002053D6B7940>]],
  5. dtype=object)

png

其他内容请参考Pandas中文文档

https://www.pypandas.cn/docs/user_guide/visualization.html#plot-formatting


本文转载自: https://blog.csdn.net/m0_52316372/article/details/127190718
版权归原作者 timerring 所有, 如有侵权,请联系我们删除。

“Python基础(十二) | 还不会python绘图?两万字博文教你Matplotlib库(超详细总结)”的评论:

还没有评论