让每个直方图 bin 具有不同的颜色

Have each histogram bin with a different color

我绘制了一个直方图,并希望每个分箱都具有不同的颜色。现在我收到错误消息: “'color' 关键字参数每个数据集必须有一种颜色,但提供了 1 个数据集和 10 种颜色”

我也附上了直方图的截图。提前致谢

decades = np.arange(1910, 2020, 10)
colors = ['aqua', 'red', 'gold', 'royalblue', 'darkorange', 'green', 'purple', 'cyan', 'yellow', 'lime']

plt.figure(figsize=(12,7))
plt.hist(df.Year, bins=decades, color=colors)
plt.xticks(decades);

colors 关键字仅适用于您想要一次绘制多个数据集(=直方图)的情况。它不能用于单独为条形着色。

然而,您可以从 hist 命令捕获结果,并迭代结果以设置颜色。这允许您在需要时也可以使用值或 bin 信息(例如,根据值进行着色),但是使用您的示例来简单地分配一个唯一的颜色(基于订单)可以完成。

例如:

import matplotlib.pyplot as plt
import numpy as np

decades = np.arange(1910, 2020, 10)
data = np.random.gamma(4, scale=0.2, size=1000)*110+1910
colors = ['aqua', 'red', 'gold', 'royalblue', 'darkorange', 'green', 'purple', 'cyan', 'yellow', 'lime']

fig, ax = plt.subplots(figsize=(8,4), facecolor='w')
cnts, values, bars = ax.hist(data, edgecolor='k', bins=decades)
ax.set_xticks(decades)

for i, (cnt, value, bar) in enumerate(zip(cnts, values, bars)):
    bar.set_facecolor(colors[i % len(colors)])

或基于值的颜色:

cmap = plt.cm.viridis

for i, (cnt, value, bar) in enumerate(zip(cnts, values, bars)):
    bar.set_facecolor(cmap(cnt/cnts.max()))

  • 以下,回答的是 OP 中的数据,而不是标题。
  • 直方图最适用于连续数据(例如浮点数)。此数据是按十年计算的,因此它是离散的,这意味着这只是值计数的条形图。
  • 根据 OP,数据位于 pandas 数据帧 (df.Year) 中,因此获取 'Year'.value_counts,然后使用 pandas.DataFrame.plotkind='bar',它使用 matplotlib 作为后端。这也有 color 作为参数。
  • 测试于 python 3.8.11pandas 1.3.2matplotlib 3.4.2seaborn 0.11.2
import pandas as pd
import numpy as np

# sample data
np.random.seed(365)
data = {'Year': np.random.choice(np.arange(1910, 2020, 10), size=1100)}
df = pd.DataFrame(data)

# display(df.head())
   Year
0  1930
1  1950
2  1920
3  1960
4  1930

# get the value counts and sort
vc = df.Year.value_counts().sort_index()

# plot
colors = ['aqua', 'red', 'gold', 'royalblue', 'darkorange', 'green', 'purple', 'steelblue', 'yellow', 'lime', 'magenta']
vc.plot(kind='bar', color=colors, width=1, rot=0, ec='k')

sns.countplot

  • seaborn 是 high-level API 对于 matplotlib
  • 有了.countplot就没必要再用.value_counts()
p = sns.countplot(data=df, x='Year', palette=colors)