如何在 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屋!