【问题标题】:Matplotlib different dashed lines instead of coloured lines [duplicate]Matplotlib不同的虚线而不是彩色线[重复]
【发布时间】:2015-05-23 15:49:57
【问题描述】:

我经常需要在黑白打印机上打印图表,如果我想在同一张图表上显示不同的数据集,matplotlib 使用的默认不同颜色对我没有帮助。

有没有办法改变 matplotlib 的默认设置,以循环通过一系列不同的虚线变体,就像在技术出版物中经常看到的那样,而不是循环通过不同颜色的线?

非常感谢您对此的帮助。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以使用 itertools 模块来循环线条样式

    import matplotlib.pyplot as plt
    import itertools
    
    # put all the linestyles you want in the list below (non exhaustive here)
    style=itertools.cycle(["-","--","-.",":",".","h","H"])
    
    
    # assuming xseries and yseries previously created (each one is a list of lists)
    for x,y in zip(xseries,yseries):
        plt.plot(x,y,"b"+style.next())
    plt.show()
    

    【讨论】:

    • 正是我想要的,谢谢!
    • 最好通过kwargs ax.plot(x, y, color='b', linestyle=style.next())传递颜色和线型。类似 MATLAB 的样式字符串非常适合交互式使用,但对于脚本来说,最好是显式的。
    • itertools.cycle().next() 在 python3 中被删除以支持next(itertools.cycle())
    【解决方案2】:

    matplotlib文档具有更改线形状的一个非常好的例子:

    http://matplotlib.org/users/pyplot_tutorial.html#controlling-line-properties

    构建一个函数不会难以从循环物质中从列表中返回或产生一个值的函数。

    来自文档中的示例:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # evenly sampled time at 200ms intervals
    t = np.arange(0., 5., 0.2)
    
    # red dashes, blue squares and green triangles
    plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
    plt.show()
    

    在图表上生成三种不同的颜色和形状的线条。

    【讨论】:

    • 这意味着您需要在手中键入每个。 span>
    • 不是特别的手。 \jk。我打算将示例代码作为如何更改行类型的示例。这伴随着It wouldn't be overly difficult to build a function which returns or yields one of the values from a list in a cyclic matter.,它旨在建议设计类似于@ manu190466的功能。 span>
    猜你喜欢
    • 1970-01-01
    • 2019-11-29
    • 2018-08-16
    • 2021-10-24
    • 1970-01-01
    • 2023-03-14
    • 2012-04-28
    • 1970-01-01
    相关资源
    最近更新 更多