【问题标题】:Cannot set spine line style with matplotlib无法使用 matplotlib 设置脊线样式
【发布时间】:2019-07-10 00:56:35
【问题描述】:

我尝试设置matplotlib plot spins的线条样式,但由于某种原因,它不起作用。我可以将它们设置为不可见或使它们变细,但我无法更改线条样式。

我的目标是将一个情节分成两部分,以在顶部显示异常值。我想将各自的底部/顶部刺设置为点状,以便它们清楚地表明存在中断。

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)

我希望上面的代码可以绘制顶部图的底部脊椎和底部图的顶部脊椎虚线。

我错过了什么?

【问题讨论】:

    标签: python matplotlib linestyle


    【解决方案1】:

    第一个应该提到,如果你不改变线宽,虚线样式显示很好。

    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 点 = 100 dpi 时的 1 个像素)并将颜色改为浅灰色可能是有意义的。

    【讨论】:

    • 如你所说,为什么虚线样式在应用于脊椎时如此紧?如果你在同一个图中绘制一条线,它的线型就会松散很多。有没有办法从一条线上获取破折号间距,例如为了将它应用到脊椎? (简单地尝试line.get_linestyle() 不起作用,因为它只会返回'--'。)
    • @ErlendM 非常好的问题。我相应地更新了答案。因此,假设您在情节中有一个line,并且有一个spine 以使其具有相同的风格,您会选择spine.set_linestyle(line.get_linestyle()); spine.set_linewidth(line.get_linewidth()); spine.set_capstyle(line.get_dash_capstyle())
    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多