图中曲线之间的阴影区域

Den*_*ang 4 python matplotlib

所以我有几条曲线由相同的 x 值定义,但不同的 y 值。下图由 21 条不同的曲线组成。其中10条是虚线,1条是实线,最后10条是虚线。

然而,从图中可以看出,它在一张图中相当多。你真的看不到到处都是什么。所以我想要的是在前 10 行和最后 10 行之间有一个阴影区域,我认为这会让眼睛更容易。

但我不太确定如何开始?

现在我的代码如下:

import os
import numpy as np
import matplotlib.pyplot as plt

structures = ['Rectum']
patients = ["426"]

color_map = 'nipy_spectral'
color = {'PTV':0.16, 'Rectum':0.80, 'Bladder':0.96}

legends = ['PTV', 'Rectum', 'Bladder']

x = np.loadtxt('dose_gy.txt')


for plot, patient in enumerate(patients):
    plot += 1
    PATH_TO_YDATA = 'results/Two_Fields/DVH'
    for f in sorted(os.listdir(PATH_TO_YDATA), key=lambda f: f.split('_')[-2]):
        if f.split('_')[-2] == patient:
            for structure in structures:
                if f.split('_')[2] == structure:
                    y = np.loadtxt(PATH_TO_YDATA + '/' + f)
                    plt.axis([0, 90, 0, 50])
                    if int(f.split('_')[-1][:-4]) < 90:
                        plt.plot(x, y * 100, color=plt.get_cmap(color_map)(color[structure]), linestyle='dotted', alpha=0.8, linewidth=2.0)
                    elif int(f.split('_')[-1][:-4]) > 90:
                        plt.plot(x, y * 100, color=plt.get_cmap(color_map)(color[structure]), linestyle='dashed', alpha=0.8, linewidth=2.0)
                    elif int(f.split('_')[-1][:-4]) == 90:
                        plt.plot(x, y * 100, color=plt.get_cmap(color_map)(color[structure]), linestyle='solid', alpha=1.0, linewidth=3.0, zorder=1000)
    plt.title('Patient ' + str(plot))
    plt.xlabel("Dose [Gy]", fontsize=14)
    plt.ylabel("Volume [%]", fontsize=14)


plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Imp*_*est 6

为了填充几条曲线的最小值和最大值之间,您需要确定代表曲线上每个点的最小值或最大值的数组。如果所有曲线共享相同的 x 值,这很容易通过沿组合 y 值的一个轴取最小值来完成。例如

np.min(np.c_[y1, y2, y3, ...], axis=1)
Run Code Online (Sandbox Code Playgroud)

最大值相同。然后fill_between可以将这些组合数组用作输入。

一个完整的例子:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(4)

# generate some data to plot
x = np.linspace(0.8,10,201)
f = lambda x, p1,p2,p3,p4: p1/x + np.sinc(x*p4)*p3 + p2
Y = np.empty((len(x), 9))
P1 = 1.5+ (np.random.normal(size=9)-0.5)*0.2
P2 = np.linspace(0.9,1.1, 9)
P3 = 1+ (np.random.normal(size=9)-0.5)*0.2
P4 = np.linspace(0.9,1.1, 9)+ (np.random.normal(size=9)-0.5)
for i in range(9):
    Y[:,i] = f(x,P1[i], P2[i], P3[i], P4[i])

# plot    
fig, ax = plt.subplots()

style= [":"]*4 + ["-"] + ["--"]*4
colors = ["crimson"]*4 + ["k"] + ["#9a0bad"]*4
lw = np.ones(9); lw[4] = 2
for i in range(9):
    ax.plot(x,Y[:,i], linestyle=style[i], label="curve "+str(i), lw=lw[i], color=colors[i])

Y1min = np.min(Y[:,:4], axis=1)
Y1max = np.max(Y[:,:4], axis=1)
Y2min = np.min(Y[:,5:], axis=1)
Y2max = np.max(Y[:,5:], axis=1)

ax.fill_between(x, Y1max, Y1min, color="crimson", alpha=0.4)
ax.fill_between(x, Y2max, Y2min, color="#9a0bad", alpha=0.4)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明