如何使用颜色图在一个图上绘制多个图并迭代不同的颜色图
我需要为不同的传感器使用不同的颜色映射。我打算把这些颜色映射放在一个列表里,然后在循环中调用它们。每个传感器的颜色映射显示的是该传感器测量的温度范围。
到目前为止,我在实现这个功能时遇到了一些困难。我可以在循环中指定一个通用的颜色映射,比如说“Blues”,但我不知道怎么在循环中遍历不同的颜色映射。
cmap = ['Blues', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds']
for j, n in enumerate(sensor_number):
fig = plt.figure(str(n), figsize=[10,6])
for k, T in enumerate(Temp):
xs = np.linspace(t[0], t[-1], 1000)
ys = model_funct(xs, *param[k][j])
plt.plot(xs, ys, label="Standard Linear Model", color='k', linestyle='dashed
cm = plt.cm.Blues(np.linspace(0.5, 0.8, len(Temp)))
for i in range(len(Temp)):
plt.scatter(t, R, s=0.5, label="Experimental Data", color=cm[i])
#plt.savefig(dir + '\\Graphs\\' + str(n) + 'hj.png')
plt.show()
这里,t和R是我的数据。
我简化并删减了很多代码的部分,以便展示问题,所以代码在某些地方可能看起来有点多余。
另外,使用等高线图会不会更好呢?不同的等高线表示不同的温度。
1 个回答
0
这里有两个例子,展示了如何把颜色图(colormap)作为对象传递和使用。第一个例子是按照你的方法,为每个传感器使用单独的图和颜色图。但如果用同一个颜色图来表示所有数据,可能会让数据更容易理解,所以我展示了如何在所有传感器之间共享一个颜色图。
我对一个做法非常有感触,特别是对于实验或传感器数据:这些数据应该总是带着所有的标识符和元数据存储和传递,不管你怎么理解这些信息。也就是说,任何你需要的东西,都应该能帮助你重建数据的来源。尽量在任何可以的地方都把这些信息加上——比如写传感器数据到文件的结构、图片的文件名、那些可以裁剪掉的简短文字说明,但实际上它们总是“真实”存在的……任何东西。数据很容易搞混,但只要你一开始就设置好,自动给所有东西加标签是很简单的。让电脑来处理那些无聊又重复的工作吧!
import matplotlib.pyplot as plt
import numpy.random as rand
import matplotlib.cm as cmap
# Dummy sensors
sensor_numbers = (213, 902, 34)
cmaps = [cmap.summer, cmap.winter, cmap.inferno]
sensor_colors = zip(sensor_numbers, cmaps)
#dummy data for each sensor
# I like keeping data "tied" to its ID in one structure;
# dictionaries are flexible builtins
sensor_data = dict()
rand.seed(20240304)
N = 12
for n, c in sensor_colors:
#making up (x, y, c) array data
#pandas.DataFrame allows meaningful column names for more readable code
sensor_data[n] = [rand.rand(N), rand.rand(N), n * rand.rand(N), c] # different color ranges
for i in sensor_data:
fig, ax = plt.subplots( figsize=[3.5, 2])
scatter = ax.scatter(sensor_data[i][0], sensor_data[i][1],
s=20, c = sensor_data[i][2],
cmap=sensor_data[i][3])
fig.colorbar(scatter, ax=ax)
fig.suptitle("Data from sensor " + str(i))
plt.savefig("multiple_colormaps_"+str(i)+".png")
# or! if you want to compare all the sensor's data,
# you actually want the *same* colormap for all of them
# find the limits of *all* the data
# before we can plot *any* data with the right color:
cmin, cmax = 10, 10
for i in sensor_data:
cmin = min(min(sensor_data[i][2]), cmin)
cmax = max(max(sensor_data[i][2]), cmax)
norm = plt.Normalize(cmin, cmax)
shapes = ('1', 8, '+') # zip these IDs into sensor_data in place of the colormaps
for a, b in zip(sensor_numbers, shapes):
sensor_data[a].append(b)
fig, ax = plt.subplots(figsize=[6, 4])
for i in sensor_data:
scatter = ax.scatter(sensor_data[i][0], sensor_data[i][1],
s=20, c = sensor_data[i][2],
label=i, marker=sensor_data[i][4],
cmap=cmap.winter, norm=norm)
fig.colorbar(scatter, ax=ax)
ax.legend()
fig.suptitle("Experimental data")
plt.savefig("multiple_colormaps_shared.png")
第一个方法的结果:
共享的颜色条: