# Matplotlib Python 中的線型

Suraj Joshi 2024年2月15日

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

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