noc*_*mbi 2 python matplotlib linestyle
我尝试设置 matplotlib 绘图脊线的线条样式,但由于某种原因,它不起作用。我可以将它们设置为不可见或使它们变细,但我无法更改线条样式。

我的目标是将一个图分成两部分以在顶部显示异常值。我想将各自的底部/顶部刺设置为虚线,以便它们清楚地表明存在中断。
import numpy as np
import matplotlib.pyplot as plt
# Break ratio of the bottom/top plots respectively
ybreaks = [.25, .9]
figure, (ax1, ax2) = plt.subplots(
nrows=2, ncols=1,
sharex=True, figsize=(22, 10),
gridspec_kw = {'height_ratios':[1 - ybreaks[1], ybreaks[0]]}
)
d = np.random.random(100)
ax1.plot(d)
ax2.plot(d)
# Set the y axis limits
ori_ylim = ax1.get_ylim()
ax1.set_ylim(ori_ylim[1] * ybreaks[1], ori_ylim[1])
ax2.set_ylim(ori_ylim[0], ori_ylim[1] * ybreaks[0])
# Spine formatting
# ax1.spines['bottom'].set_visible(False) # This works
ax1.spines['bottom'].set_linewidth(.25) # This works
ax1.spines['bottom'].set_linestyle('dashed') # This does not work
ax2.spines['top'].set_linestyle('-') # Does not work
ax2.spines['top'].set_linewidth(.25) # Works
plt.subplots_adjust(hspace=0.05)
Run Code Online (Sandbox Code Playgroud)
我希望上面的代码绘制顶部图的底部脊柱和底部图的顶部脊柱虚线。
我想念什么?
第一个应该提到的是,如果您不更改线宽,虚线样式显示正常。
ax1.spines['bottom'].set_linestyle("dashed")
Run Code Online (Sandbox Code Playgroud)
但是间距可能有点太紧。这是因为默认情况下capstyle设置"projecting"为脊椎。
因此,可以将 设置capstyle为"butt"(这也是图中法线的默认值),
ax1.spines['bottom'].set_linestyle('dashed')
ax1.spines['bottom'].set_capstyle("butt")
Run Code Online (Sandbox Code Playgroud)
或者,可以进一步分离破折号。例如
ax1.spines['bottom'].set_linestyle((0,(4,4)))
Run Code Online (Sandbox Code Playgroud)
现在,如果您还将线宽设置得更小,那么您将需要按比例增加间距。例如
ax1.spines['bottom'].set_linewidth(.2)
ax1.spines['bottom'].set_linestyle((0,(16,16)))
Run Code Online (Sandbox Code Playgroud)
请注意,由于使用了抗锯齿,屏幕上的线条实际上并没有变细。它只是洗掉,使其颜色变浅。因此,总的来说,将线宽保持在 0.72 点(0.72 点 = 100 dpi 时的 1 个像素)并将颜色改为浅灰色可能是有意义的。