如何在matplotlib中将数字转换为色标? [英] How can I convert numbers to a color scale in matplotlib?
问题描述
我正在绘制条形图,我希望条形的颜色根据颜色渐变从红色变为蓝色.我有一个数据框的尺寸,可以告诉我每个条形图应在红蓝色标度上的哪个位置.我当前的方法是通过在RGB红色和蓝色之间进行线性插值,将这些值手动转换为RGB颜色,但是我想要一种将数值转换为色标的自动方法.我还需要有一个颜色条图例来帮助解释它.
I'm making a bar plot and I want the colors of the bars to vary from red to blue according to a color gradient. I have a dimension of the data frame that tells me where on the red-blue scale each bar should be. My current method is to manually convert these values to RGB colors by linearly interpolating between the RGB red and blue colors but I want an automatic way of converting my numeric values to a color scale. I also need to be able to have a colorbar legend to help interpret it.
推荐答案
创建条形图并根据数据框中的值设置条形颜色非常简单.色彩图和规范化实例有助于将值转换为颜色,matplotlib.Axes.bar
的color
参数可以理解.然后使用与色条相同的归一化和颜色图从ScalarMappable
创建色条.
It's pretty straight forward to create a barchart and set the bar colors according to a value from the dataframe. A colormap and a normalization instance help converting the values to colors, which are understood by the color
argument of matplotlib.Axes.bar
. The colorbar is then created from a ScalarMappable
using the same normalization and colormap as the bars.
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np; np.random.seed(0)
import pandas as pd
x = np.arange(12)
y = np.random.rand(len(x))*51
c = np.random.rand(len(x))*3+1.5
df = pd.DataFrame({"x":x,"y":y,"c":c})
cmap = plt.cm.rainbow
norm = matplotlib.colors.Normalize(vmin=1.5, vmax=4.5)
fig, ax = plt.subplots()
ax.bar(df.x, df.y, color=cmap(norm(df.c.values)))
ax.set_xticks(df.x)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([]) # only needed for matplotlib < 3.1
fig.colorbar(sm)
plt.show()
要使用带有条形图的自定义颜色图,请参见根据颜色图着色的条形图?
For using a custom colormap with bar plots see Barplot colored according a colormap?
这篇关于如何在matplotlib中将数字转换为色标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!