无法使用matplotlib设置脊椎线样式

2024-05-13 23:39:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图设置matplotlib绘图脊椎的线条样式,但由于某些原因,它不起作用。我可以设置为不可见或使其变薄,但不能更改线样式。在

no dotted spines

我的目标是将一个图分成两个,以显示顶部的异常值。我希望将相应的底部/顶部脊椎设置为虚线,以便它们清楚地显示存在中断。在

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)

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

我错过了什么?在


Tags: 绘图matplotlibtopplt样式thissetbottom
1条回答
网友
1楼 · 发布于 2024-05-13 23:39:20

首先需要指出的是,如果不更改线宽,则虚线样式显示良好。在

ax1.spines['bottom'].set_linestyle("dashed")

enter image description here

但是间距可能有点太紧了。这是因为对于脊椎,capstyle默认设置为"projecting"。在

因此,可以将capstyle设置为"butt"(这也是绘图中法线的默认设置)

^{pr2}$

enter image description here

或者,可以进一步分离破折号。E、 g

ax1.spines['bottom'].set_linestyle((0,(4,4)))

enter image description here

现在,如果你把线宽设得更小,你就需要相应地增加间距。E、 g

ax1.spines['bottom'].set_linewidth(.2)  
ax1.spines['bottom'].set_linestyle((0,(16,16))) 

enter image description here

请注意,由于使用了抗锯齿处理,屏幕上的线条实际上不会变细。它只是被洗掉了,所以颜色变浅了。因此,总的来说,将线宽保持在0.72点(0.72点=100 dpi时的1个像素)并将颜色改为浅灰色是有意义的。在

相关问题 更多 >