【问题标题】:Matplotlib/pyplot: easy way for conditional formatting of linestyle?Matplotlib/pyplot:线条样式条件格式的简单方法?
【发布时间】:2021-02-03 20:42:13
【问题描述】:

假设我想绘制两条相互交叉的实线,并且仅当 line2 在第一行上方时才绘制虚线。这些线位于同一个 x 网格上。实现这一目标的最佳/最简单方法是什么?我可以在绘制之前将 line2 的数据拆分为两个对应的数组,但我想知道是否有更直接的方法来设置某种条件线型格式?

小例子:

import numpy as np
import matplotlib.pyplot as plt

x  = np.arange(0,5,0.1)
y1 = 24-5*x
y2 = x**2

plt.plot(x,y1)
plt.plot(x,y2)#dashed if y2 > y1?!
plt.show()

对于更复杂的场景有相关的问题,但我正在为这个标准案例寻找最简单的解决方案。有没有办法直接在 plt.plot() 中执行此操作?

【问题讨论】:

  • 也许您可以找到线条相交的位置,在该索引处分割您想要破折号的线条,然后使用plt.plot(x, y, linestyle="dashed")
  • 是的,这是我目前的解决方法。但是,我想知道是否有更简单或更直接的方法来实现这一点。

标签: python matplotlib plot linestyle


【解决方案1】:

@Sameeresque 很好地解决了它。

这是我的看法:

import numpy as np
import matplotlib.pyplot as plt

def intersection(list_1, list_2):
    shortest = list_1 if len(list_1) < len(list_2) else list_2
    indexes = []
    for i in range(len(shortest)):
        if list_1[i] == list_2[i]:
            indexes.append(i)
    return indexes


plt.style.use("fivethirtyeight")

x  = np.arange(0, 5, 0.1)
y1 = 24 - 5*x
y2 = x**2
intersection_point = intersection(y1, y2)[0]  # In your case they only intersect once


plt.plot(x, y1)

x_1 = x[:intersection_point+1]
x_2 = x[intersection_point:]
y2_1 = y2[:intersection_point+1]
y2_2 = y2[intersection_point:]

plt.plot(x_1, y2_1)
plt.plot(x_2, y2_2, linestyle="dashed")

plt.show()

与@Sammeresque 原理相同,但我认为他的解决方案更简单。

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x  = np.arange(0,5,0.1)
    y1 = 24-5*x
    y2 = x**2
    
    xs2=x[y2>y1]
    xs1=x[y2<=y1]
    plt.plot(x,y1)
    plt.plot(xs1,y2[y2<=y1])
    plt.plot(xs2,y2[y2>y1],'--')#dashed if y2 > y1?!
    plt.show()
    

    【讨论】:

    • 非常感谢!这是一个简洁、实用的解决方案。但是,它仍然需要对数据进行一些“预处理”。所以我认为这也回答了我问题的第二部分:没有简单的方法可以在一个命令中设置条件线型格式(?)。
    猜你喜欢
    • 2020-12-29
    • 1970-01-01
    • 2012-11-01
    • 2017-11-18
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 2013-07-29
    相关资源
    最近更新 更多