linestyle参数介绍
linestyle参数用来设置线的线型,设置时有两种方式,第一种是传递线型名称,例如传递linestyle=‘solid’。第二种方式更加通用,使用传递格式为**(offset, (on_off_seq))**的元组进行线型设置。其中offset指定偏移量,一般设置为0。(on_off_seq)是一个2元元组,包含2*N个元素,奇数项元素指定点数量,偶数项元素指定空位点数量。例如(3, 10, 1, 10)表示3pt点,10pt点空位,1pt点,10pt点空位。linestyle示例程序如下:
import numpy as np
import matplotlib.pyplot as plt
#线性名称
linestyle_str = [
('solid', 'solid'), # 同 (0, ()) or '-'
('dotted', 'dotted'), # 同 (0, (1, 1)) or '.'
('dashed', 'dashed'), # 同 as '--'
('dashdot', 'dashdot')] # 同 '-.'
#使用通用方式
linestyle_tuple = [
('loosely dotted', (0, (1, 10))),
('dotted', (0, (1, 1))),
('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))),
('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))),
('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))]
def plot_linestyles(ax, linestyles, title):
X, Y = np.linspace(0, 100, 10), np.zeros(10)
yticklabels = []
for i, (name, linestyle) in enumerate(linestyles):
ax.plot(X, Y+i, linestyle=linestyle, linewidth=1.5, color='black')
yticklabels.append(name)
ax.set_title(title)
ax.set(ylim=(-0.5, len(linestyles)-0.5),
yticks=np.arange(len(linestyles)),
yticklabels=yticklabels)
ax.tick_params(left=False, bottom=False, labelbottom=False)
ax.spines[:].set_visible(False)
for i, (name, linestyle) in enumerate(linestyles):
ax.annotate(repr(linestyle),
xy=(0.0, i), xycoords=ax.get_yaxis_transform(),
xytext=(-6, -12), textcoords='offset points',
color="blue", fontsize=8, ha="right", family="monospace")
ax0, ax1 = (plt.figure(figsize=(10, 8))
.add_gridspec(2, 1, height_ratios=[1, 3])
.subplots())
plot_linestyles(ax0, linestyle_str[::-1], title='Named linestyles')
plot_linestyles(ax1, linestyle_tuple[::-1], title='Parametrized linestyles')
plt.tight_layout()
plt.show()