我尝试设置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)
我期望上面的代码绘制顶部地块的底部脊椎和底部地块的顶部脊椎。
我错过了什么?
发布于 2019-02-16 05:17:57
首先要指出的是,如果不更改线宽,虚线样式显示良好。
ax1.spines['bottom'].set_linestyle("dashed")
然而,间距可能有点太紧了。这是由于脊椎的capstyle
默认设置为"projecting"
。
因此可以改为将capstyle
设置为"butt"
(这也是曲线图中的法线的默认值),
ax1.spines['bottom'].set_linestyle('dashed')
ax1.spines['bottom'].set_capstyle("butt")
或者,可以进一步分隔破折号。例如。
ax1.spines['bottom'].set_linestyle((0,(4,4)))
现在,如果您还将线宽设置为更小的值,那么您将需要按比例增加间距。例如。
ax1.spines['bottom'].set_linewidth(.2)
ax1.spines['bottom'].set_linestyle((0,(16,16)))
请注意,由于使用了抗锯齿功能,屏幕上的线条实际上并没有变得更细。它只是洗掉了,所以它的颜色变得更浅了。因此,总的来说,将线宽保持在0.72点(0.72点=100dpi时的1个像素)并将颜色更改为浅灰色可能是有意义的。
https://stackoverflow.com/questions/54716821
复制相似问题