如何用对应于渐变颜色的值来改变多条线的颜色?

时间:2019-04-09 07:52:57

标签: python matplotlib colors line

我有成千上万的线,并且每条线的值都在0到1之间,与某个要素相关。我要做的是绘制这些线条,并同时通过颜色显示它们的功能。也就是说,如果线条的值为0.5,那么我希望此线条具有颜色条的中间颜色。如何构建此代码?以下是一个示例。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(111)

x = np.linspace(0, 1, 100)
b_range=np.linspace(0, 1, 5)

for j in range(len(b_range)):
    b=b_range[j]
t=b+(1-b)*(1-x)/(1-0)   
ax.plot(x, t,color="red")


plt.show()

2 个答案:

答案 0 :(得分:1)

使用cmap中的颜色图:

import numpy as np

from matplotlib import pyplot as plt
from matplotlib import colors

fig, ax = plt.subplots(figsize=(6, 6))

cdict = {'red':   ((0.0,  0.22, 0.0),
                   (0.5,  1.0, 1.0),
                   (1.0,  0.89, 1.0)),

         'green': ((0.0,  0.49, 0.0),
                   (0.5,  1.0, 1.0),
                   (1.0,  0.12, 1.0)),

         'blue':  ((0.0,  0.72, 0.0),
                   (0.5,  0.0, 0.0),
                   (1.0,  0.11, 1.0))}

cmap = colors.LinearSegmentedColormap('custom', cdict)

for i in np.linspace(0, 1):
    # Plot 50 lines, from y = 0 to y = 1, taking a corresponding value from the cmap
    ax.plot([-1, 1], [i, i], c=cmap(i))

enter image description here

here中提供了完整的颜色表列表。

答案 1 :(得分:0)

您可以使用Color变量控件自行更改颜色

这是一个例子

import numpy as np
import matplotlib.pyplot as plt


def format_axes(ax):
    ax.margins(0.2)
    ax.set_axis_off()

points = np.ones(5)  # Draw 5 points for each line
text_style = dict(horizontalalignment='right', verticalalignment='center',
                  fontsize=12, fontdict={'family': 'monospace'})
COLOR = (0, 0, 0.1)

def color_conv(color_range):
    return (COLOR[0] + color_range, COLOR[1], COLOR[2]) 

# Plot all line styles.
fig, ax = plt.subplots()

for color_ite in range(10):   
    ax.text(-0.1, color_ite, '-', **text_style)
    ax.plot(color_ite * points, color=color_conv(color_ite/10), linewidth=3)
    format_axes(ax)
    ax.set_title('line styles')

plt.show()

输出:

enter image description here