首页 > 解决方案 > 如何根据 Matplotlib 中接近 1.0 的数字为每条绘制的线选择新颜色

问题描述

我想在下面绘制类似代码的内容(** 请参阅此 **)。所以颜色是基于每个函数的单个数字。然后我想在颜色图中显示它。就像在示例绘图形式 Matplotlib 中一样

th = np.linspace(0, 2*np.pi, 128)

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

ax.plot(th, np.cos(th), **color = 0.98**) # darker color cause close to 1.0
# in the line the color should not change just every line another color!
ax.plot(th, np.sin(th), **color = 0.80**) # lighter color cause not so close to 1.0

与此类似:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib import colors as mcolors

N = 50
x = np.arange(N)
# Here are many sets of y to plot vs x
ys = [x + i for i in x]

# We need to set the plot limits, they will not autoscale
fig, ax = plt.subplots()
ax.set_xlim(np.min(x), np.max(x))
ax.set_ylim(np.min(ys), np.max(ys))

line_segments = LineCollection([np.column_stack([x, y]) for y in ys],
                               linewidths=(0.5, 1, 1.5, 2),
                               linestyles='solid')
line_segments.set_array(x)
ax.add_collection(line_segments)
axcb = fig.colorbar(line_segments)
axcb.set_label('Line Number')
ax.set_title('Line Collection with mapped colors')
plt.sci(line_segments)  # This allows interactive changing of the colormap.
plt.show()

标签: pythonmatplotlibplotcolors

解决方案


这是一些演示代码,可能会满足您的要求。curve_labels 和 curve_colors 只是说明如何根据您的情况调整颜色条。正如@ImportanceOfBeingErnest 在评论中提到的,plasma_r可能是一个有吸引力的配色方案,较深的颜色接近 1。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

th = np.linspace(0, 2*np.pi, 128)

curve_labels = ['sin(t)', 'sin(t)/2', 'sin(3*t)', 'sin(4*t)']
curve_colors = [  .98,       .10,       .80,        .40]

cmap = cm.get_cmap('plasma_r')
fig, ax = plt.subplots(figsize=(7, 7))

ax.plot(th, np.sin(th), color=cmap(.98))
ax.plot(th, np.sin(th)/2, color=cmap(.10))
ax.plot(th, np.sin(3*th), color=cmap(.80))
ax.plot(th, np.sin(4*th), color=cmap(.40))

ax.set_title('Curves with mapped colors')
cbar = plt.colorbar(cm.ScalarMappable(norm=None, cmap=cmap), ax=ax, ticks=curve_colors)
cbar.ax.set_yticklabels(curve_labels)

plt.show()

结果图


推荐阅读