python - 在 matplotlib 中,我如何绘制一条多色线,如彩虹

标签 python matplotlib

我想绘制不同颜色的平行线。例如。而不是一条粗细为 6 的红线,我想要两条粗细为 3 的平行线,一条红色一条蓝色。 任何想法将不胜感激。
谢谢

即使使用智能偏移(如下所示),在连续点之间具有锐角的 View 中仍然存在问题。

智能偏移的缩放 View : issue with sharp angles in line

不同粗细的叠加线: the inbuilt linewidth functionality sorts this automatically, somehow

最佳答案

绘制平行线并非易事。使用简单的统一偏移量当然不会显示所需的结果。如下左图所示。
这样一个简单的偏移量可以在 matplotlib 中产生,如 transformation tutorial 所示。 .

enter image description here

方法1

更好的解决方案可能是使用右侧的草图。要计算第 n 点的偏移量,我们可以使用法向量到 n-1st 和 n+1 之间的线st点,并沿此法向量使用相同的距离来计算偏移点。

这种方法的优点是我们在原始线中的点数与偏移线中的点数相同。缺点是不完全准确,如图所示。

该方法在下面代码中的offset函数中实现。
为了使它对 matplotlib 绘图有用,我们需要考虑线宽应该独立于数据单元。线宽通常以点为单位给出,偏移量最好以相同的单位给出,例如可以满足问题的要求(“两条宽度为 3 的平行线”)。 因此,想法是使用 ax.transData.transform 将坐标从数据转换为显示坐标。点 o 的偏移量也可以转换为相同的单位:使用 dpi 和 ppi=72 的标准,显示坐标的偏移量是 o*dpi/ppi .应用显示坐标偏移后,逆变换 (ax.transData.inverted().transform) 允许进行反向变换。

现在问题的另一个维度:如何确保偏移量保持不变,而与图形的缩放和大小无关? 最后一点可以通过每次发生缩放事件时重新计算偏移量来解决。

这是用这种方法产生的彩虹曲线的样子。

enter image description here

这是生成图像的代码。

import numpy as np
import matplotlib.pyplot as plt

dpi = 100

def offset(x,y, o):
    """ Offset coordinates given by array x,y by o """
    X = np.c_[x,y].T
    m = np.array([[0,-1],[1,0]])
    R = np.zeros_like(X)
    S = X[:,2:]-X[:,:-2]
    R[:,1:-1] = np.dot(m, S)
    R[:,0] = np.dot(m, X[:,1]-X[:,0])
    R[:,-1] = np.dot(m, X[:,-1]-X[:,-2])
    On = R/np.sqrt(R[0,:]**2+R[1,:]**2)*o
    Out = On+X
    return Out[0,:], Out[1,:]


def offset_curve(ax, x,y, o):
    """ Offset array x,y in data coordinates
        by o in points """
    trans = ax.transData.transform
    inv = ax.transData.inverted().transform
    X = np.c_[x,y]
    Xt = trans(X)
    xto, yto = offset(Xt[:,0],Xt[:,1],o*dpi/72. )
    Xto = np.c_[xto, yto]
    Xo = inv(Xto)
    return Xo[:,0], Xo[:,1]


# some single points
y = np.array([1,2,2,3,3,0])    
x = np.arange(len(y))
#or try a sinus
x = np.linspace(0,9)
y=np.sin(x)*x/3.


fig, ax=plt.subplots(figsize=(4,2.5), dpi=dpi)

cols = ["#fff40b", "#00e103", "#ff9921", "#3a00ef", "#ff2121", "#af00e7"]
lw = 2.
lines = []
for i in range(len(cols)):
    l, = plt.plot(x,y, lw=lw, color=cols[i])
    lines.append(l)


def plot_rainbow(event=None):
    xr = range(6); yr = range(6); 
    xr[0],yr[0] = offset_curve(ax, x,y, lw/2.)
    xr[1],yr[1] = offset_curve(ax, x,y, -lw/2.)
    xr[2],yr[2] = offset_curve(ax, xr[0],yr[0], lw)
    xr[3],yr[3] = offset_curve(ax, xr[1],yr[1], -lw)
    xr[4],yr[4] = offset_curve(ax, xr[2],yr[2], lw)
    xr[5],yr[5] = offset_curve(ax, xr[3],yr[3], -lw)

    for i  in range(6):     
        lines[i].set_data(xr[i], yr[i])


plot_rainbow()

fig.canvas.mpl_connect("resize_event", plot_rainbow)
fig.canvas.mpl_connect("button_release_event", plot_rainbow)

plt.savefig(__file__+".png", dpi=dpi)
plt.show()


方法2

为避免重叠线,必须使用更复杂的解决方案。 可以首先偏移与它所属的两条线段垂直的每个点(下图中的绿点)。然后计算通过这些偏移点的线并找到它们的交点。 enter image description here

一个特殊的情况是两个连续线段的斜率相等。必须注意这一点(eps 在下面的代码中)。

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

dpi = 100

def intersect(p1, p2, q1, q2, eps=1.e-10):
    """ given two lines, first through points pn, second through qn,
        find the intersection """
    x1 = p1[0]; y1 = p1[1]; x2 = p2[0]; y2 = p2[1]
    x3 = q1[0]; y3 = q1[1]; x4 = q2[0]; y4 = q2[1]
    nomX = ((x1*y2-y1*x2)*(x3-x4)- (x1-x2)*(x3*y4-y3*x4)) 
    denom = float(  (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4) )
    nomY = (x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)
    if np.abs(denom) < eps:
        #print "intersection undefined", p1
        return np.array( p1 )
    else:
        return np.array( [ nomX/denom , nomY/denom ])


def offset(x,y, o, eps=1.e-10):
    """ Offset coordinates given by array x,y by o """
    X = np.c_[x,y].T
    m = np.array([[0,-1],[1,0]])
    S = X[:,1:]-X[:,:-1]
    R = np.dot(m, S)
    norm = np.sqrt(R[0,:]**2+R[1,:]**2) / o
    On = R/norm
    Outa = On+X[:,1:]
    Outb = On+X[:,:-1]
    G = np.zeros_like(X)
    for i in xrange(0, len(X[0,:])-2):
        p = intersect(Outa[:,i], Outb[:,i], Outa[:,i+1], Outb[:,i+1], eps=eps)
        G[:,i+1] = p
    G[:,0] = Outb[:,0]
    G[:,-1] = Outa[:,-1]
    return G[0,:], G[1,:]


def offset_curve(ax, x,y, o, eps=1.e-10):
    """ Offset array x,y in data coordinates
        by o in points """
    trans = ax.transData.transform
    inv = ax.transData.inverted().transform
    X = np.c_[x,y]
    Xt = trans(X)
    xto, yto = offset(Xt[:,0],Xt[:,1],o*dpi/72., eps=eps )
    Xto = np.c_[xto, yto]
    Xo = inv(Xto)
    return Xo[:,0], Xo[:,1]


# some single points
y = np.array([1,1,2,0,3,2,1.,4,3]) *1.e9   
x = np.arange(len(y))
x[3]=x[4]
#or try a sinus
#x = np.linspace(0,9)
#y=np.sin(x)*x/3.


fig, ax=plt.subplots(figsize=(4,2.5), dpi=dpi)

cols = ["r", "b"]
lw = 11.
lines = []
for i in range(len(cols)):
    l, = plt.plot(x,y, lw=lw, color=cols[i], solid_joinstyle="miter")
    lines.append(l)


def plot_rainbow(event=None):
    xr = range(2); yr = range(2); 
    xr[0],yr[0] = offset_curve(ax, x,y,  lw/2.)
    xr[1],yr[1] = offset_curve(ax, x,y, -lw/2.)

    for i  in range(2):     
        lines[i].set_data(xr[i], yr[i])


plot_rainbow()

fig.canvas.mpl_connect("resize_event", plot_rainbow)
fig.canvas.mpl_connect("button_release_event", plot_rainbow)

plt.show()

enter image description here

请注意,只要线之间的偏移小于线上后续点之间的距离,此方法就可以正常工作。否则方法 1 可能更适合。

关于python - 在 matplotlib 中,我如何绘制一条多色线,如彩虹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42165631/

相关文章:

python - xticks matplotlib 中的四舍五入日期时间

python - 转换 pd.DataFrame : Lists to strings

python - scikit-learn 中纵向/面板数据的交叉验证

python - 无法在 matplotlib 图中出现次要网格线

python - Matplotlib 通过颜色或形状区分均值和中值

python - 如何绘制多元线性回归的最佳拟合平面?

python - 如何让我的 TCP 服务器永远运行?

python - 将 crontab 与 django 一起使用

Python列表——去重和添加子列表元素

python-2.7 - 如何从 matplotlib 工具栏更新图例