首先,我对 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
对象类型的参数。
我可能让它变得比实际更难,所以我将不胜感激任何更清晰或更正确的方法。
最佳答案
要获得条形图根据颜色图着色的条形图,您可以使用 bar(x,y, color=colors)
的 color
参数,其中 colors
是一个包含所有颜色的柱的长度列表。 IE。该列表中的第 i
个条目是第 i
个柱的颜色。
为了从颜色图创建此列表,您需要使用相应的值调用颜色图。
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()
关于python - 根据颜色图着色的条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42656585/