【发布时间】:2017-03-07 19:21:53
【问题描述】:
首先,我对 Matplotlib 或 Seaborn 中的颜色非常陌生。我的目的是创建一个带有根据自定义调色板着色的条形图。像这样,但使用我的自定义调色板(见下文,红色、橙色、绿色和蓝色的调色板):
我已经使用LinearSegmentedColormap 方法创建了我的自定义顺序调色板,但我无法在简单的plt.barplot() 中使用它。当然这并不难,但我看不到路。我使用下面的函数创建了调色板,来自这个线程:Create own colormap using matplotlib and plot color scale
def make_colormap(seq):
"""Return a LinearSegmentedColormap
seq: a sequence of floats and RGB-tuples. The floats should be increasing
and in the interval (0,1).
"""
seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
cdict = {'red': [], 'green': [], 'blue': []}
for i, item in enumerate(seq):
if isinstance(item, float):
r1, g1, b1 = seq[i - 1]
r2, g2, b2 = seq[i + 1]
cdict['red'].append([item, r1, r2])
cdict['green'].append([item, g1, g2])
cdict['blue'].append([item, b1, b2])
return mcolors.LinearSegmentedColormap('CustomMap', cdict)
#main#
c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
[c('red'), 0.125, c('red'), c('orange'), 0.25, c('orange'),c('green'),0.5, c('green'),0.7, c('green'), c('blue'), 0.75, c('blue')])
N = 1000
array_dg = np.random.uniform(0, 10, size=(N, 2))
colors = np.random.uniform(0, 5, size=(N,))
plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb)
plt.colorbar()
plt.show()
返回这个情节:
据我所知,我不能将颜色图(来自 LinearSegmentedColormap()? 的对象类型)用于条形图,但颜色图是我实现自定义顺序调色板的独特方式。
总之,我想将第二个图(散点图)的颜色图应用到第一个图(条形图)。现在我不能这样做,因为barplot() 函数没有接受LinearSegmentedColormap 对象类型的参数。
我可能让它变得比实际更难,所以我会很感激任何更清洁或更正确的方法。
【问题讨论】:
-
我根本看不到问题所在。代码工作正常。这里的问题到底是什么?
-
对不起,可能没有充分解释我的问题。我想知道如何在条形图中使用此颜色图,例如“plt.barplot(x, y, color="my_custom_colormap")。正如您在第一条评论中看到的那样,调色板在散点图中工作正常( plt. scatter(...c = colors, cmap = rvb) )。问题是在 barplot 函数中没有像“cmap”这样的参数。
-
在您的代码中,您有一个散点图,而不是条形图。您希望条形图中的颜色代表哪个数量?请edit您的问题反映问题本身,而不是实际工作正常的问题。
-
你的缩进全错了。请修复它
标签: python matplotlib plot seaborn