【问题标题】:How can I set the dash length in a matplotlib contour plot如何在 matplotlib 等高线图中设置虚线长度
【发布时间】:2012-09-15 04:12:56
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    差不多了。

    是:

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

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

    也许线条样式的定义发生了一些变化,并且您使用的是旧示例。

    collections documentation 有话要说:

    • set_dashes(ls)

      set_linestyle 的别名

    • set_linestyle(ls)

      设置集合的线型。

      接受:[‘实心’| “虚线”、“虚线”、“虚线” | (offset, on-off-dash-seq)]

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

    【讨论】:

    • 非常感谢!我也厌倦了 (offset,(on,off)) 格式,但我没有意识到我需要方括号内的括号。我的情节现在看起来很棒。你让我今天很开心。谢谢,丹
    【解决方案2】:

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

    【讨论】:

    • 这是 matplotlib 3 的变化吗?使用 MPL 版本 2.2.2 之前的答案仍然适用于我。此外,我必须将 lines.dashed_style 更改为 lines.dashed_pattern 才能正常工作。
    • @DanHickstein 如果你想保存 eps 格式,问题就来了。
    • 明白了。 dashed_styledashed_pattern 是否也会随着 eps 格式而变化?
    • @DanHickstein 是的,我尝试使用dashed_style 的开关模式,但它不起作用,所以dashed_style 应该只是默认模式之一,然后dashed_pattern可以使用开关格式。
    猜你喜欢
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2014-09-09
    • 2017-07-12
    相关资源
    最近更新 更多