如何在matplotlib等高线图中设置虚线的长度

9
我正在使用matplotlib制作一些等高线图,但虚线的长度太长了,点状线看起来也不好。我想手动设置虚线的长度。当我使用plt.plot()绘制简单的图时,我可以设置确切的虚线长度,但是我无法弄清如何在等高线图中实现同样的效果。
我认为下面的代码应该可以工作,但我收到了错误提示:
File "/Library/Python/2.7/site-packages/matplotlib-1.2.x-py2.7-macosx-10.8-intel.egg/matplotlib/backends/backend_macosx.py", line 80, in draw_path_collection
    offset_position)
TypeError: failed to obtain the offset and dashes from the linestyle

这里是一个我想要实现的示例,改编自MPL示例:
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt


delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

plt.figure()

CS = plt.contour(X, Y, Z, 6, colors='k',linestyles='dashed')

for c in CS.collections:
    c.set_dashes([2,2])

plt.show()

谢谢!

2个回答

12

Almost.

It's:

for c in CS.collections:
    c.set_dashes([(0, (2.0, 2.0))])

如果你在那里放置了print c.get_dashes(),你就会发现(这就是我所做的)。
也许线条样式的定义有些变化,你可能是按照旧的例子来工作的。 集合文档中有这样的说明:
  • set_dashes(ls)

    设置集合的线型别名为 set_linestyle

  • set_linestyle(ls)

    设置集合的线型。

    接受值:[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) ]

因此,在[(0,(2.0,2.0))] 中,0 是偏移量,元组是循环的开/关模式。

非常感谢!我也尝试过(offset,(on,off))的格式,但我没有意识到需要在方括号内加上括号。现在我的图表看起来很棒。你让我的一天变得美好了。谢谢,丹。 - DanHickstein

2

虽然这是一个老问题,但我不得不处理它,当前的答案已经不再有效。更好的方法是在绘图之前使用plt.rcParams ['lines.dashed_style'] = [2.0,2.0]


1
这是Matplotlib 3的更改吗?对我来说,先前的答案仍然有效,使用MPL版本2.2.2。此外,我必须将lines.dashed_style更改为lines.dashed_pattern才能使其工作。 - DanHickstein
@DanHickstein 如果您想保存EPS格式,可能会遇到问题。 - anishtain4
明白了。dashed_styledashed_pattern在eps格式下也会改变吗? - DanHickstein
@DanHickstein 是的,我试图使用 dashed_style 的开关模式,但它没有起作用,所以 dashed_style 应该只是默认样式之一,然后 dashed_pattern 可以使用开关格式。 - anishtain4

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