如何设置matplotlib等高线p中的短划线长度

2024-03-28 15:43:26 发布

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

我正在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()

谢谢!


Tags: theinimportmatplotlibasnppltmacosx
2条回答

差不多了。

它是:

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

如果你把一个print c.get_dashes()放在那里,你就会发现(我就是这么做的)。

也许线条样式的定义有点变化,您是从一个旧的示例开始工作的。

collections documentation的意思是:

  • set_dashes(ls)

    alias for set_linestyle

  • set_linestyle(ls)

    Set the linestyle(s) for the collection.

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

所以在[(0, (2.0, 2.0))]中,0是偏移量,然后元组是on-off重复模式。

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

相关问题 更多 >