首页 > 解决方案 > 如何绘制部分彩色的线?

问题描述

如图所示,如何根据 x 的特定值绘制具有不同颜色的线?

在此处输入图像描述

标签: matplotlib

解决方案


这里最简单的解决方案可能是在np.wherex_lim找到的相应索引处对数据进行切片:

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0,2*np.pi,100)
y = np.cos(x)*np.exp(-x/2)

# specify your x limitation
x_lim = np.pi
# find the first corresponding idx where the condition x>=x_lim hold
x_lim_idx = np.where(x>=x_lim)[0][0]

# plot sliced data
plt.plot(x[:x_lim_idx],y[:x_lim_idx],'r')
plt.plot(x[x_lim_idx:],y[x_lim_idx:],'b')

这给出了x_lim = np.pi

output_sliced

如果线条之间的剩余间隙困扰您,x例如对于小的离散化,您仍然可以通过使两个切片重叠来关闭它。


推荐阅读