# Matplotlib Python 中的线型

Suraj Joshi 2021年7月18日 2020年11月24日

## 在 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()
``````

``````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 `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()
``````

Author: Suraj Joshi

Suraj Joshi is a backend software engineer at Matrice.ai.