gpt4 book ai didi

python - 如何根据matplotlib中的颜色图对散点图进行着色?

转载 作者:IT老高 更新时间:2023-10-28 20:51:24 24 4
gpt4 key购买 nike

我正在尝试根据从已定义的颜色图中选择的一组值(从 0 到 1)对散点图中的点进行着色,例如蓝色或红色。我试过这个:

import matplotlib
import matplotlib.pyplot as plt
from numpy import *
from scipy import *
fig = plt.figure()
mymap = plt.get_cmap("Reds")
x = [8.4808517662594909, 11.749082788323497, 5.9075039082855652, 3.6156231827873615, 12.536817102137768, 11.749082788323497, 5.9075039082855652, 3.6156231827873615, 12.536817102137768]
spaced_colors = linspace(0, 1, 10)
print spaced_colors
plt.scatter(x, x,
color=spaced_colors,
cmap=mymap)
# this does not work either
plt.scatter(x, x,
color=spaced_colors,
cmap=plt.get_cmap("gray"))

但它不起作用,使用红色或灰色 map 。如何做到这一点?

edit:如果我想分别绘制每个点以便它可以有一个单独的图例,我该怎么做?我试过了:

fig = plt.figure()
mymap = plt.get_cmap("Reds")
data = np.random.random([10, 2])
colors = list(linspace(0.1, 1, 5)) + list(linspace(0.1, 1, 5))
print "colors: ", colors
plt.subplot(1, 2, 1)
plt.scatter(data[:, 0], data[:, 1],
c=colors,
cmap=mymap)
plt.subplot(1, 2, 2)
# attempt to plot first five points in five shades of red,
# with a separate legend for each point
for n in range(5):
plt.scatter([data[n, 0]], [data[n, 1]],
c=[colors[n]],
cmap=mymap,
label="point %d" %(n))
plt.legend()

但它失败了。我需要为每个点调用 scatter 以便它可以有一个单独的 label=,但仍然希望每个点都有不同的颜色图阴影作为它的颜色。谢谢。

最佳答案

如果你真的想这样做(你在编辑中描述的内容),你必须从你的颜色图中“提取”颜色(我已经评论了我对你的代码所做的所有更改):

import numpy as np
import matplotlib.pyplot as plt

# plt.subplots instead of plt.subplot
# create a figure and two subplots side by side, they share the
# x and the y-axis
fig, axes = plt.subplots(ncols=2, sharey=True, sharex=True)
data = np.random.random([10, 2])
# np.r_ instead of lists
colors = np.r_[np.linspace(0.1, 1, 5), np.linspace(0.1, 1, 5)]
mymap = plt.get_cmap("Reds")
# get the colors from the color map
my_colors = mymap(colors)
# here you give floats as color to scatter and a color map
# scatter "translates" this
axes[0].scatter(data[:, 0], data[:, 1], s=40,
c=colors, edgecolors='None',
cmap=mymap)
for n in range(5):
# here you give a color to scatter
axes[1].scatter(data[n, 0], data[n, 1], s=40,
color=my_colors[n], edgecolors='None',
label="point %d" %(n))
# by default legend would show multiple scatterpoints (as you would normally
# plot multiple points with scatter)
# I reduce the number to one here
plt.legend(scatterpoints=1)
plt.tight_layout()
plt.show()

colored-scatter

但是,如果您只想绘制 10 个值并且想要命名每个值,您应该考虑使用不同的东西,例如条形图 example .另一个机会是将 plt.plot 与自定义颜色循环一起使用,例如 example .

关于python - 如何根据matplotlib中的颜色图对散点图进行着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11885060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com