迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Matplotlib Python 中的线型

作者:迹忆客 最近更新:2023/03/17 浏览次数:

本文主要介绍了我们如何在 Matplotlib plot 中通过设置 matplotlib.pyplot.plot() 方法中 linestyle 参数的适当值来使用不同的线型。我们有很多 linestyle 的选项。

在 Matplotlib Python 中设置线条样式

import math
import numpy as np
import matplotlib.pyplot as plt 

x=np.linspace(0,2*math.pi,100)
y=np.sin(x)

plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("sinx")
plt.title("Sinx Function")
plt.show()

输出:

Matplotlib Python 中的默认线条样式

它以默认的实线样式生成 sinx 函数的图形。

要查看 linestyle 参数的选择,我们可以执行以下脚本。

from matplotlib import lines
print(lines.lineStyles.keys())

输出:

dict_keys(['-', '--', '-.', ':', 'None', ' ', ''])

我们可以使用任何一个输出值来改变图形的线型。

import math
import numpy as np
import matplotlib.pyplot as plt 

x=np.linspace(0,2*math.pi,100)
y=np.sin(x)

plt.plot(x,y,linestyle='-.')
plt.xlabel("x")
plt.ylabel("sinx")
plt.title("Sinx Function")
plt.show()

输出:

在 Matplotlib Python 中设置线型

它将我们绘图中的线条样式设置为 -.

Matplotlib Linestyle 文档提供了一个字典,我们可以用它来对线型进行更精细的控制。根据文档,我们可以用 (offset, (on_off_seq)) 元组来设置行样式。

import math
import numpy as np
import matplotlib.pyplot as plt 

from collections import OrderedDict

linestyles_dict = OrderedDict(
    [('solid',               (0, ())),
     ('loosely dotted',      (0, (1, 10))),
     ('dotted',              (0, (1, 5))),
     ('densely dotted',      (0, (1, 1))),

     ('loosely dashed',      (0, (5, 10))),
     ('dashed',              (0, (5, 5))),
     ('densely dashed',      (0, (5, 1))),

     ('loosely dashdotted',  (0, (3, 10, 1, 10))),
     ('dashdotted',          (0, (3, 5, 1, 5))),
     ('densely dashdotted',  (0, (3, 1, 1, 1))),

     ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
     ('dashdotdotted',         (0, (3, 5, 1, 5, 1, 5))),
     ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))])

x=np.linspace(0,2*math.pi,100)
y=np.sin(x)

plt.plot(x,y,linestyle=linestyles_dict['loosely dashdotdotted'])
plt.xlabel("x")
plt.ylabel("sinx")
plt.title("Sinx Function")
plt.show()

输出:

在 Matplotlib Python 中使用字典设置线条样式

它使用 linestyles_dict 字典设置 linestyle。我们可以选择任何我们想要设置线型的键,并将该键的值传递给 linestyles_dict 字典,作为 plot() 方法中的 linestyle 参数。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便