Matplotlib / pyplot:线型条件格式的简便方法?

问题描述

比方说,我想绘制两条相互交叉的实线,并且仅当虚线2位于线1上方时才想绘制虚线2。这些线在同一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()

Minimal Example

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

解决方法

enter image description here 您可以尝试这样的事情:

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()
,

@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,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一样,但我认为他的解决方案更简单。

preview