无法使用matplotlib设置脊线样式

3
我尝试设置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)

我希望以上代码能够绘制顶部图的底部脊柱和底部图的顶部脊柱虚线。

我错过了什么?

1个回答

8

首先需要提到的是,如果您不更改线宽度,则虚线样式显示得很好。

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像素),并将颜色改为浅灰色可能更合适。


为什么当应用于脊柱时,虚线样式会变得如此紧密呢?如果在同一图中绘制一条线,则其线型要松散得多。是否有一种方法可以从一条线中获取虚线间距,例如以便将其应用于脊柱?(简单地尝试 line.get_linestyle() 是行不通的,因为它只返回 '--'。) - Erlend Magnus Viggen
1
@ErlendM 很好的问题。我相应地更新了答案。所以说,如果你在图中有一条“线”,并且有一个“脊柱”使其样式相同,你可以选择类似于spine.set_linestyle(line.get_linestyle()); spine.set_linewidth(line.get_linewidth()); spine.set_capstyle(line.get_dash_capstyle())这样的东西。 - ImportanceOfBeingErnest

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接