Barplot根据色彩图进行着色?

Dan*_*llo 6 python plot matplotlib seaborn

首先,我对Matplotlib或Seaborn的颜色很新.我的目的是创建一个条形图,其条形图根据自定义调色板着色.这样的东西,但我的自定义调色板(见下面,红色,橙色,绿色和蓝色的调色板):

barplot

我已经使用该LinearSegmentedColormap方法创建了自定义顺序调色板,但我无法在简单中使用它plt.barplot().当然不难,但我看不出路.我使用下面的函数创建了调色板,从这个线程获得:使用matplotlib创建自己的颜色图并绘制颜色比例

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()
Run Code Online (Sandbox Code Playgroud)

这返回了这个情节:

情节调色板好

据我所知,我不能使用色图(来自LinearSegmentedColormap()?的对象类型)作为条形图,但色彩图是我实现自定义顺序调色板的独特方式.

总之,我想将第二个图(散点图)的色图应用到第一个图(条形图).现在我不能这样做,因为barplot()函数没有接受LinearSegmentedColormap对象类型的参数.

我可能比现在更难,所以我会感谢任何更清洁或更正确的方式.

Imp*_*est 10

要获得条形图,其中条形图根据颜色图而着色,您可以使用color参数bar(x,y, color=colors),其中colors包含所有颜色的条形长度列表.即该i列表中的条目是该条的颜色i.
要从colormap创建此列表,您需要使用相应的值调用colormap.

在此输入图像描述

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np

clist = [(0, "red"), (0.125, "red"), (0.25, "orange"), (0.5, "green"), 
         (0.7, "green"), (0.75, "blue"), (1, "blue")]
rvb = mcolors.LinearSegmentedColormap.from_list("", clist)

N = 60
x = np.arange(N).astype(float)
y = np.random.uniform(0, 5, size=(N,))

plt.bar(x,y, color=rvb(x/N))
plt.show()
Run Code Online (Sandbox Code Playgroud)


Ema*_*uel 5

Seabornbarplot非常适合这个,例如

ax = sns.barplot("size", y="total_bill", data=tips, palette="Blues_d")
Run Code Online (Sandbox Code Playgroud)