小能豆

更改 matplotlib 中刻度的 capstyle

py

我想使用圆形的 capstyle 来表示刻度。我尝试了以下方法,但不起作用。

import matplotlib.pyplot as plt   
# better tick visiblity to check the capstyle
plt.rcParams.update({
           'figure.dpi': 150,
          u'xtick.major.size': 5.0,
          u'xtick.major.width': 2,
          })

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4])

tl = ax.xaxis.get_ticklines()    
for i in tl:
    i.set_solid_capstyle('round')
plt.show()

阅读 70

收藏
2025-02-21

共1个答案

小能豆

因此,这不起作用的原因是刻度标记是用刻度作为标记实现的单点线。

In [127]: [i.get_linestyle() for i in ax.xaxis.get_ticklines()]
Out[127]: 
['None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None']

In [128]: [i.get_marker() for i in ax.xaxis.get_ticklines()]
Out[128]: [2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3]

参见文档以了解 ints -> shape 之间的映射,这是交替的“tickup”和“tickdown”。

这确实可以让你做一些半可爱的事情,例如

[i.set_marker('o') for i in ax.xaxis.get_ticklines()]

由此得出1.png


如果你使用这个,当上游中断时,这将是你的问题

为了得到你想要的东西,你可以深入研究并在刻度标记上设置 capstyle:

for i in ax.xaxis.get_ticklines():
    # reach in and poke the guts 
    # USE AT YOUR OWN RISK
    i._marker._capstyle = 'round' 
    # this is not officially supported

请注意,这使用的不是 1 个,而是 2 个私有属性,明年即将推出的 traitlet 重构(针对 v2.1)会破坏该属性。这也将被重新设置为on'butt'调用的硬编码值_recache(我不记得它何时被调用)。

我不认为你真的想这样做:

2.png

因为它使刻度的两端都变圆,而不仅仅是指向内的一侧(但也许较小的刻度尺寸,圆润的“向外”一侧会被脊柱隐藏)

2025-02-21