如下程序实现了条形图的颜色渐变,类似于矩阵热力图。

官网:https://matplotlib.org/api/_as_gen/matplotlib.colors.LinearSegmentedColormap.html?highlight=from_list#matplotlib.colors.LinearSegmentedColormap.from_list

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

df = pd.DataFrame({"x" : np.random.rand(10)*10})
# cmap实际上是一个可以将数值映射为颜色的线性函数
cmap = mcolors.LinearSegmentedColormap.from_list("", ["red", "yellow", "green"])

plt.bar(df.index, df["x"], color=cmap(df.x.values/df.x.values.max()))
plt.xlabel('Column', labelpad=12)
plt.tight_layout()
plt.show(
View Code

相关文章: