【问题标题】:Have each histogram bin with a different color使每个直方图箱具有不同的颜色
【发布时间】:2021-11-04 05:10:30
【问题描述】:

我绘制了一个直方图,并希望每个 bin 都有不同的颜色。现在我收到错误消息: “'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);

【问题讨论】:

    标签: python pandas matplotlib seaborn histogram


    【解决方案1】:

    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()))
    

    【讨论】:

    • 非常感谢 Rutger 的解释!
    【解决方案2】:
    • 以下内容是回答 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

    • seabornmatplotlib 的高级 API
    • 有了.countplot,就不需要使用.value_counts()
    p = sns.countplot(data=df, x='Year', palette=colors)
    

    【讨论】:

      猜你喜欢
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 2020-08-30
      相关资源
      最近更新 更多