python - 如何根据 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()
解决方案
这是一些演示代码,可能会满足您的要求。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()
推荐阅读
- mysql - 如何在 SQL 中创建日期占位符?
- lmdb - 在 LMDB 中,事务是读取它刚刚写入的值还是旧值?
- c++ - C ++“使用”关键字用于唯一类型而不是别名
- c++ - 可变参数模板错误:“在实例化中”(gcc 9.2)
- c++ - 是否可以避免每次都链接 gsl 和 openmp?
- python - TKinter Matplotlib 图不显示
- tensorflow - ANN - 低性能
- reactjs - 第一次提交表单后如何将formik中的validateOnChange和validateOnBlur更改为true?
- java - 使用邻接矩阵的 BFS
- python - pygame 使用 Class 实例循环移动