在MatPlotLib中检索自定义虚线

5

有许多问题涉及如何通过Line2D.set_linestyleLine2D.set_dashes在matplotlib线条中设置自定义破折号。然而,我似乎找不到一种在设置后检索虚线图案的方法。

以下是在主网站上设置虚线的示例,在下面我将参考此示例: http://matplotlib.org/examples/lines_bars_and_markers/line_demo_dash_control.html。代码已在此处复制以便于清晰理解:

"""
Demo of a simple plot with a custom dashed line.

A Line object's ``set_dashes`` method allows you to specify dashes with
a series of on/off lengths (in points).
"""
import numpy as np
import matplotlib.pyplot as plt


x = np.linspace(0, 10)
line, = plt.plot(x, np.sin(x), '--', linewidth=2)

dashes = [10, 5, 100, 5]  # 10 points on, 5 off, 100 on, 5 off
line.set_dashes(dashes)

plt.show()

没有line.get_dashes方法。调用line.get_linestyle返回'--'。如何使用MatPlotLib 1.5.1检索实际的虚线模式?

更新

对于那些关心我为什么会这样问的人:我正在尝试使用dashrule包创建一个简单的线型转LaTeX转换器。最初的灵感来自于这个问题/答案。如果我可以避免使用线型并直接获取虚线和线宽度,那就太好了。

我已经学会了如何使用tikz制作标记,因此最终希望能够将图例元素添加到轴标签中。通过更多的研究和努力,我希望将所有内容合并到MatPlotLib的PR中。

更新 #2

似乎有一个Line2D的“私有”属性_dashSeq,其中包含我正在寻找的序列。但是,如果我设置预设样式之一,例如,该属性值不会更改。

>>> line.set_linestyle((0, (2, 5, 7, 3)))
>>> line.get_linestyle()  # This seems expected behavior for custom dash
'--'
>>> line._dashSeq         # This is what I want
(2, 5, 7, 3)
>>> line.set_linestyle('--')
>>> line.get_linestyle()  # This reflects reality now
'--'
>>> line._dashSeq         # This no longer does
(2, 5, 7, 3)

问题在于我现在无法区分这两种风格(预设与自定义),因此我的问题仍然存在。

报价是故意的。 - Mad Physicist
这是一段代码,最近一直在接受大量的折磨(并最终耦合到绘图上下文中)。 - tacaswell
所以没有快速而肮脏的方法来做到这一点吗?此外,您认为TeX基础传说可以放置在标签等位置的PR是否有任何价值?我正在考虑要么这样做,要么找出一种让传说的所有元素都接受旋转的方法,以便我可以做到这一点:https://dev59.com/S5jga4cB1Zd3GeqPIVLJ。但两者似乎都很棘手。 - Mad Physicist
@tcaswell。我在考虑以下公共API的解决方法,如果合理,请告知:当设置预设线条样式之一时,将_dashSeq设置为None,并添加一个公共的get_dashseq方法来检索样式。这样,get_dashseqget_linestyle相结合,就可以告诉您有关线条样式的所有信息。 - Mad Physicist
这可能需要积极更新虚线模式,因为设置线宽、线型或虚线模式时都会受到影响(参见https://github.com/matplotlib/matplotlib/issues/6592)。 - tacaswell
1个回答

1

我知道这是一个老问题,但当我试图解决类似的问题时,我发现受保护的属性已经更改了名称(为_unscaled_dash_pattern_dash_pattern),并且完全遵循了预期的逻辑。换句话说,我认为问题已经自行解决。

注:

  • 我正在使用matplotlib 3.7.1。
  • _dash_pattern会随着线宽进行缩放。据我所知,这是为了确保点是正方形的。

示例:

>>> line.set_linestyle((0, (2, 5, 7, 3)))
>>> line.get_linestyle()         # Expected behaviour for custom dash
'--'
>>> line._unscaled_dash_pattern  # This is what was needed
(0, (2, 5, 7, 3))
>>> line._dash_pattern           # This is the scaled version (lw=0.5)
(0.0, [1.0, 2.5, 3.5, 1.5])
>>> line.set_linestyle('--')
>>> line.get_linestyle()         # Still expected behaviour
'--'
>>> line._unscaled_dash_pattern  # Now contains updated dash pattern
(0.0, (3.7, 1.6))

送上好消息永远不会太晚 :) 非常感激。 - Mad Physicist

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