Python 您所在的位置:网站首页 散列表怎么画出来的图像 Python

Python

2024-07-11 11:06| 来源: 网络整理| 查看: 265

 

 

from matplotlib import pyplot as plt

(1) 折线图 

plt.plot([1, 2, 3, 2, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]) plt.show()

`matplotlib.pyplot.plot(*args, **kwargs)` 方法严格来讲可以绘制线形图或者样本标记。其中,`*args` 允许输入单个 y 值或 x, y值。

(2) 正弦曲线图

X = np.linspace(-2*np.pi,2*np.pi,1000) Y = np.sin(X) plt.plot(X,Y)

 

 

(3) 柱形图

# 柱形图 plt.bar([1, 2, 3], [1, 2, 3],width=0.3,color='red')

 

(4)散点图

#散点图 # X,y 的坐标均有 numpy 在 0 到 1 中随机生成 1000 个值 X = np.random.ranf(1000) y = np.random.ranf(1000) # 向方法中 `*args` 输入 X,y 坐标 plt.scatter(X, y,edgecolors='green')

(5)饼状图

# 饼状图 plt.pie([1,2,3,4,5])

(6) 量场图  ,  就是由向量组成的图像,在气象学等方面被广泛应用。从图像的角度来看,量场图就是带方向的箭头符号。

X, y = np.mgrid[0:10, 0:10] plt.quiver(X, y)

(7) 等高线图

# 生成网格矩阵 x = np.linspace(-5, 5, 500) y = np.linspace(-5, 5, 500) X, Y = np.meshgrid(x, y) # 等高线计算公式 Z = (1 - X / 2 + X ** 3 + Y ** 4) * np.exp(-X ** 2 - Y ** 2) plt.contourf(X, Y, Z)

定义图形样式

上面,我们绘制了简单的基础图形,但这些图形都不美观。你可以通过更多的参数来让图形变得更漂亮。

二维线性图 比较常用的一些参数 (详细-> 参数) : 

参数含义alpha=设置线型的透明度,从 0.0 到 1.0color=设置线型的颜色fillstyle=设置线型的填充样式linestyle=设置线型的样式linewidth=设置线型的宽度marker=设置标记点的样式…………

(1) 三角函数图像

# 在 -2PI 和 2PI 之间等间距生成 1000 个值,也就是 X 坐标 X = np.linspace(-2 * np.pi, 2 * np.pi, 1000) # 计算 sin() 对应的纵坐标 y1 = np.sin(X) # 计算 cos() 对应的纵坐标 y2 = np.cos(X) # 向方法中 `*args` 输入 X,y 坐标 plt.plot(X, y1, color='r', linestyle='--', linewidth=2, alpha=0.8) plt.plot(X, y2, color='b', linestyle='-', linewidth=2)

(2) 散点图  (官方参数网址)

参数含义s=散点大小c=散点颜色marker=散点样式cmap=定义多类别散点的颜色alpha=点的透明度edgecolors=散点边缘颜色 # 生成随机数据 x = np.random.rand(100) y = np.random.rand(100) colors = np.random.rand(100) size = np.random.normal(50, 60, 10) plt.scatter(x, y, s=size, c=colors) # 绘制散点图

(3)  饼状图      通过 matplotlib.pyplot.pie() 绘出。我们也可以进一步设置它的颜色、标签、阴影等各类样式。

# 饼状图 label = 'Cat', 'Dog', 'Cattle', 'Sheep', 'Horse' # 各类别标签 color = 'r', 'g', 'r', 'g', 'y' # 各类别颜色 size = [1, 2, 3, 4, 5] # 各类别占比 explode = (0, 0, 0, 0, 0.2) # 各类别的偏移半径 # 绘制饼状图 plt.pie(size, colors=color, explode=explode, labels=label, shadow=True, autopct='%1.1f%%') # 饼状图呈正圆 plt.axis('equal')

 

 

组合图形样式 x = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] y_bar = [3, 4, 6, 8, 9, 10, 9, 11, 7, 8] y_line = [2, 3, 5, 7, 8, 9, 8, 10, 6, 7] plt.bar(x, y_bar) plt.plot(x, y_line, '-o', color='y')

定义图形位置

在图形的绘制过程中,你可能需要调整图形的位置,或者把几张单独的图形拼接在一起。此时,我们就需要引入 plt.figure 图形对象了。

x = np.linspace(0, 10, 20) # 生成数据 y = x * x + 2 fig = plt.figure() # 新建图形对象 axes = fig.add_axes([0.5, 0.5, 0.8, 0.8]) # 控制画布的左, 下, 宽度, 高度 axes.plot(x, y, 'r')

x = np.linspace(0, 10, 20) # 生成数据 y = x * x + 2 fig = plt.figure() # 新建画板 axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # 大画布 axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # 小画布 axes1.plot(x, y, 'r') # 大画布 axes2.plot(y, x, 'g') # 小画布

在这里,figure 相当于绘画用的画板,而 axes 则相当于铺在画板上的画布。我们将图像绘制在画布上,于是就有了 plot,set_xlabel 等操作。

 借助于图形对象,我们可以实现大图套小图的效果。

上面的绘图代码中, add_axes() 方法向我们设置的画板 figure 中添加画布 axes。在 Matplotlib 中,还有一种添加画布的方式,那就是 plt.subplots(),它和 axes 都等同于画布。

fig, axes = plt.subplots() axes.plot(x, y, 'r')

借助于 plt.subplots(),我们就可以实现子图的绘制,也就是将多张图按一定顺序拼接在一起。

x = np.linspace(0, 10, 20) # 生成数据 y = x * x + 2 fig, axes = plt.subplots(nrows=1, ncols=2) # 子图为 1 行,2 列 for ax in axes: ax.plot(x, y, 'r')

通过设置 plt.subplots 的参数,可以实现调节画布尺寸和显示精度。

fig, axes = plt.subplots( figsize=(16, 9), dpi=50) # 通过 figsize 调节尺寸, dpi 调节显示精度 axes.plot(x, y, 'r') 规范绘图方法

首先,任何图形的绘制,都建议通过 plt.figure() 或者 plt.subplots() 管理一个完整的图形对象。而不是简单使用一条语句,例如 plt.plot(...) 来绘图。

添加图标题、图例

绘制包含图标题、坐标轴标题以及图例的图形,举例如下:

x = np.linspace(0, 10, 20) # 生成数据 y = x * x + 2 fig, axes = plt.subplots() axes.set_xlabel('x label') # 横轴名称 axes.set_ylabel('y label') axes.set_title('title') # 图形名称 axes.plot(x, x**2) axes.plot(x, x**3) axes.legend(["y = x**2", "y = x**3"], loc=0) # 图例

图例中的 loc 参数标记图例位置,1,2,3,4 依次代表:右上角、左上角、左下角,右下角;0 代表自适应

线型、颜色、透明度

fig, axes = plt.subplots() axes.plot(x, x+1, color="red", alpha=0.8) axes.plot(x, x+2, color="#1155dd") axes.plot(x, x+3, color="#15cc55")

而对于线型而言,除了实线、虚线之外,还有很多丰富的线型可供选择。

fig, ax = plt.subplots(figsize=(12, 6)) # 线宽 ax.plot(x, x+1, color="blue", linewidth=0.25) ax.plot(x, x+2, color="blue", linewidth=0.50) ax.plot(x, x+3, color="blue", linewidth=1.00) ax.plot(x, x+4, color="blue", linewidth=2.00) # 虚线类型 ax.plot(x, x+5, color="red", lw=2, linestyle='-') ax.plot(x, x+6, color="red", lw=2, ls='-.') ax.plot(x, x+7, color="red", lw=2, ls=':') # 虚线交错宽度 line, = ax.plot(x, x+8, color="black", lw=1.50) line.set_dashes([5, 10, 15, 10]) # 符号 ax.plot(x, x + 9, color="green", lw=2, ls='--', marker='+') ax.plot(x, x+10, color="green", lw=2, ls='--', marker='o') ax.plot(x, x+11, color="green", lw=2, ls='--', marker='s') ax.plot(x, x+12, color="green", lw=2, ls='--', marker='1') # 符号大小和颜色 ax.plot(x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2) ax.plot(x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4) ax.plot(x, x+15, color="purple", lw=1, ls='-', marker='o', markersize=8, markerfacecolor="red") ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8, markerfacecolor="yellow", markeredgewidth=2, markeredgecolor="blue")

画布网格、坐标轴范围

fig, axes = plt.subplots(1, 2, figsize=(10, 5)) # 显示网格 axes[0].plot(x, x**2, x, x**3, lw=2) axes[0].grid(True) # 设置坐标轴范围 axes[1].plot(x, x**2, x, x**3) axes[1].set_ylim([0, 60]) axes[1].set_xlim([2, 5])

除了折线图,Matplotlib 还支持绘制散点图、柱状图等其他常见图形。下面,我们绘制由散点图、梯步图、条形图、面积图构成的子图。 

n = np.array([0, 1, 2, 3, 4, 5]) # 1 行 4 列 fig, axes = plt.subplots(1, 4, figsize=(16, 5)) axes[0].scatter(x, x + 0.25*np.random.randn(len(x))) axes[0].set_title("scatter") axes[1].step(n, n**2, lw=2) axes[1].set_title("step") axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5) axes[2].set_title("bar") axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5) axes[3].set_title("fill_between")

图形标注方法

当我们绘制一些较为复杂的图像时,阅读对象往往很难全面理解图像的含义。而此时,图像标注往往会起到画龙点睛的效果。图像标注,就是在画面上添加文字注释、指示箭头、图框等各类标注元素。

Matplotlib 中,文字标注的方法由 matplotlib.pyplot.text() 实现。最基本的样式为 matplotlib.pyplot.text(x, y, s),其中 x, y 用于标注位置定位,s 代表标注的字符串。除此之外,你还可以通过 fontsize= , horizontalalignment= 等参数调整标注字体的大小,对齐样式等。

下面,我们举一个对柱形图进行文字标注的示例。

fig, axes = plt.subplots() x_bar = [10, 20, 30, 40, 50] # 柱形图横坐标 y_bar = [0.5, 0.6, 0.3, 0.4, 0.8] # 柱形图纵坐标 bars = axes.bar(x_bar, y_bar, color='blue', label=x_bar, width=2) # 绘制柱形图 for i, rect in enumerate(bars): x_text = rect.get_x() # 获取柱形图横坐标 y_text = rect.get_height() + 0.01 # 获取柱子的高度并增加 0.01 plt.text(x_text, y_text, '%.1f' % y_bar[i]) # 标注文字

除了文字标注之外,还可以通过 matplotlib.pyplot.annotate() 方法向图像中添加箭头等样式标注。接下来,我们向上面的例子中增添一行增加箭头标记的代码。

x_bar = [10, 20, 30, 40, 50] # 柱形图横坐标 y_bar = [0.5, 0.6, 0.3, 0.4, 0.8] # 柱形图纵坐标 fig, axes = plt.subplots() bars = axes.bar(x_bar, y_bar, color='blue', label=x_bar, width=2) # 绘制柱形图 for i, rect in enumerate(bars): x_text = rect.get_x() # 获取柱形图横坐标 y_text = rect.get_height() + 0.01 # 获取柱子的高度并增加 0.01 plt.text(x_text, y_text, '%.1f' % y_bar[i]) # 标注文字 # 增加箭头标注 plt.annotate('Min', xy=(32, 0.3), xytext=(36, 0.3), arrowprops=dict(facecolor='black', width=1, headwidth=7))

上面的示例中,xy=() 表示标注终点坐标,xytext=() 表示标注起点坐标。在箭头绘制的过程中,arrowprops=() 用于设置箭头样式,facecolor= 设置颜色,width= 设置箭尾宽度,headwidth= 设置箭头宽度,可以通过 arrowstyle= 改变箭头的样式。

实战  : 

参考答案 

# ----------------------------------------------------------------------------- # Copyright (c) 2015, Nicolas P. Rougier. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- import numpy as np import matplotlib.pyplot as plt plt.figure(figsize=(8, 5), dpi=80) ax = plt.subplot(111) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="Cos Function") plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="Sin Function") plt.xlim(X.min() * 1.1, X.max() * 1.1) plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) plt.ylim(C.min() * 1.1, C.max() * 1.1) plt.yticks([-1, +1], [r'$-1$', r'$+1$']) t = 2 * np.pi / 3 plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=1.5, linestyle="--") plt.scatter([t, ], [np.cos(t), ], 50, color='blue') plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', xy=(t, np.sin(t)), xycoords='data', xytext=(+10, +30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) plt.plot([t, t], [0, np.sin(t)], color='red', linewidth=1.5, linestyle="--") plt.scatter([t, ], [np.sin(t), ], 50, color='red') plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(t, np.cos(t)), xycoords='data', xytext=(-90, -50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) plt.legend(loc='upper left', frameon=False) plt.show()

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有