有许多问题涉及如何通过Line2D.set_linestyle
和Line2D.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)
问题在于我现在无法区分这两种风格(预设与自定义),因此我的问题仍然存在。
_dashSeq
设置为None
,并添加一个公共的get_dashseq
方法来检索样式。这样,get_dashseq
与get_linestyle
相结合,就可以告诉您有关线条样式的所有信息。 - Mad Physicist