如何利用Matplotlib中的彩色地图对散点图中的点进行阴影处理?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (11)

我试图在散点图中根据一组从已经定义的彩色地图中选取的值(从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"))

但它不起作用,使用红色或灰色的颜色地图。这是如何做到的呢?

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()

仍然希望每个点都有一个不同的颜色图作为颜色。

提问于
用户回答回答于

您必须从颜色图中“提取”颜色(我已经注释了我对代码所做的所有更改):

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()

用户回答回答于

例如:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

x, y, colors = np.random.random((3,10))

fig, ax = plt.subplots()
ax.scatter(x, y, c=colors, s=50, cmap=mpl.cm.Reds)

plt.show()

扫码关注云+社区