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

举报
timerring 发表于 2022/10/07 09:41:07 2022/10/07
【摘要】 ⭐本专栏旨在对Python的基础语法进行详解,精炼地总结语法中的重点,详解难点,面向零基础及入门的学习者,通过专栏的学习可以熟练掌握python编程,同时为后续的数据分析,机器学习及深度学习的代码能力打下坚实的基础。🔥本文已收录于Python基础系列专栏: Python基础系列教程 欢迎订阅,持续更新。 13.0 环境配置【1】 要不要plt.show()ipython中可用魔术方法 ...

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

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

image-20221007090551954

image-20221007090608537

13.0 环境配置

【1】 要不要plt.show()

  • ipython中可用魔术方法 %matplotlib inline

  • pycharm 中必须使用plt.show()

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

png

【2】设置样式

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

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

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

png

【3】将图像保存为文件

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

png

13.1 Matplotlib库

image-20221007090619966

13.1.1 折线图

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

png

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

png

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

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

png

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

png

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

png

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

png

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

png

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

png

颜色_风格_线性 设置的简写 color_marker_linestyles = [“g*-”, “b±-”, “ko-.”, “rs:”]
x = np.linspace(0, 10, 11)
offsets = list(range(0, 8, 2))
color_marker_linestyles = ["g*-", "b+--", "ko-.", "rs:"]
for offset, color_marker_linestyle in zip(offsets, color_marker_linestyles):
    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轴
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.xlim(-1, 7)
plt.ylim(-1.5, 1.5)
(-1.5, 1.5)

png

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

png

tight 会紧凑一点

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

png

equal 会松一点

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

png

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

png

  • 调整坐标轴刻度

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

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

png

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

png

  • 调整刻度样式

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

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

png

【3】设置图形标签

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

png

【4】设置图例

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

png

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

png

【5】添加文字和箭头

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

png

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

png

13.1.2 散点图

【1】简单散点图

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

png

【2】颜色配置

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

png

颜色配置参考官方文档

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

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

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

png

【4】透明度

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

png

【例】随机漫步

from random import choice

class RandomWalk():
    """一个生产随机漫步的类"""
    def __init__(self, num_points=5000):
        self.num_points = num_points
        self.x_values = [0]
        self.y_values = [0]
    
    def fill_walk(self):
        while len(self.x_values) < self.num_points:
            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance
            
            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance            
        
            if x_step == 0 or y_step == 0:
                continue
            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step
            self.x_values.append(next_x)
            self.y_values.append(next_y)
rw = RandomWalk(10000)
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.figure(figsize=(12, 6))        # 设置画布大小        
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap="inferno", s=1)
plt.colorbar()
plt.scatter(0, 0, c="green", s=100)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c="red", s=100)

plt.xticks([])
plt.yticks([])
([], <a list of 0 Text yticklabel objects>)


png

13.1.3 柱形图

【1】简单柱形图

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

png

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

png

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

png

x = ["G"+str(i) for i in range(5)]
y = 1/(1+np.exp(-np.arange(5)))

colors = ['red', 'yellow', 'blue', 'green', 'gray']
plt.bar(x, y, align="center", width=0.5, alpha=0.5, color=colors)
plt.tick_params(axis="both", labelsize=13)

png

【2】累加柱形图

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

png

【3】并列柱形图

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

png

【4】横向柱形图barh

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

png

13.1.4 多子图

【1】简单多子图

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.subplot(211)
plt.plot(t1, f(t1), "bo-", markerfacecolor="r", markersize=5)
plt.title("A tale of 2 subplots")
plt.ylabel("Damped oscillation")

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), "r--")
plt.xlabel("time (s)")
plt.ylabel("Undamped")
Text(0, 0.5, 'Undamped')

png

【2】多行多列子图

x = np.random.random(10)
y = np.random.random(10)

plt.subplots_adjust(hspace=0.5, wspace=0.3)

plt.subplot(321)
plt.scatter(x, y, s=80, c="b", marker=">")

plt.subplot(322)
plt.scatter(x, y, s=80, c="g", marker="*")

plt.subplot(323)
plt.scatter(x, y, s=80, c="r", marker="s")

plt.subplot(324)
plt.scatter(x, y, s=80, c="c", marker="p")

plt.subplot(325)
plt.scatter(x, y, s=80, c="m", marker="+")

plt.subplot(326)
plt.scatter(x, y, s=80, c="y", marker="H")
<matplotlib.collections.PathCollection at 0x2052d9f63c8>

png

【3】不规则多子图

def f(x):
    return np.exp(-x) * np.cos(2*np.pi*x)


x = np.arange(0.0, 3.0, 0.01)
grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3) # 两行三列的网格

plt.subplot(grid[0, 0]) # 第一行第一列位置
plt.plot(x, f(x))

plt.subplot(grid[0, 1:]) # 第一行后两列的位置
plt.plot(x, f(x), "r--", lw=2)

plt.subplot(grid[1, :]) # 第二行所有位置
plt.plot(x, f(x), "g-.", lw=3)
[<matplotlib.lines.Line2D at 0x2052d6fae80>]

png

【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。