【问题标题】:Adding unique colors for each bar of a multi-histogram grid plot in Python在 Python 中为多直方图网格图的每个条添加唯一颜色
【发布时间】:2022-01-06 16:27:57
【问题描述】:

我正在尝试使用 Matplotlib 在 Python 中创建一个多直方图,每个类 ( bar ) 具有唯一的颜色。

我能够实现图表,但无法让条形图的颜色正常工作。这是我的代码:

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

def draw_histograms(df, variables, n_rows, n_cols):
    fig=plt.figure() # facecolor='g' changes the background color
    for i, var_name in enumerate(variables):
        ax=fig.add_subplot(n_rows,n_cols,i+1)
        df[var_name].hist(ax=ax)

    fig.tight_layout()
    fig.set_size_inches(20.5, 10.5)
    plt.show()

draw_histograms(df_final, df_final.columns, 2, 3)

这看起来像:

在 plt.figure() 中添加“facecolor”,改变背景颜色。

我的数据框:

我想要实现的目标:对于 DF 中的每一列,我显示一个图表(共 6 个)。每个直方图中的 3 个条形图描绘了情绪 - 正面、负面和中性。我希望在所有 6 个图表中描绘不同情绪的条形图有 3 种独特的颜色。

【问题讨论】:

  • 您是否尝试过df[var_name].hist(ax=ax, color=colors) 并在您的函数之前定义颜色,例如here
  • 是的,尝试过类似的方法。我收到了ValueError: color kwarg must have one color per data set. 1 data sets and 3 colors were provided

标签: python matplotlib data-visualization


【解决方案1】:

您正在绘制一个直方图,而您只有 3 个值,为这些值中的每一个创建一个高度为 1 的条形图(或者当 2 个值非常接近时创建一个高度为 2 的条形图)。将其绘制为条形图会更清楚,它确实允许每个条形图使用一种颜色。为了使事情具有可比性,在所有子图上设置相同的 x 限制可能很有用:

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

def draw_histograms(df, variables, n_rows, n_cols, bar_width=1, xmin=0, xmax=None):
    fig = plt.figure(figsize=(20.5, 10.5))
    for i, var_name in enumerate(variables):
        ax = fig.add_subplot(n_rows, n_cols, i + 1)
        # df[var_name].plot.bar(ax=ax, color=['crimson', 'gold', 'limegreen'], rot=0)
        ax.bar(x=df[var_name], height=1, width=bar_width, color=['crimson', 'gold', 'limegreen'])
        ax.set_xlim(xmin, xmax + bar_width)
        for spine in ['right', 'top']:
            ax.spines[spine].set_visible(False)
    fig.tight_layout()
    plt.show()

df = pd.DataFrame([[1186, 181, 1960, 955, 2263, 2633],
                   [664, 171, 463, 723, 381, 697],
                   [570, 152, 336, 544, 269, 492]],
                  index=['negative', 'neutral', 'positve'])
bar_width = 30
xmax = df.max().max()
draw_histograms(df, df.columns, 2, 3, bar_width=bar_width, xmax=xmax)

def draw_histograms(df, variables, n_rows, n_cols, ymin=0, ymax=None):
    fig = plt.figure(figsize=(20.5, 10.5))
    for i, var_name in enumerate(variables):
        ax = fig.add_subplot(n_rows, n_cols, i + 1)
        df[var_name].plot.bar(ax=ax, color=['crimson', 'gold', 'limegreen'], rot=0)
        ax.set_ylim(ymin, ymax)
        ax.bar_label(ax.containers[0], size=16)
        for spine in ['right', 'top']:
            ax.spines[spine].set_visible(False)
    fig.tight_layout()
    plt.show()

ymax = df.max().max()
draw_histograms(df, df.columns, 2, 3, ymax=ymax * 1.1)

也可以使用显示值的条形高度和使用 x 值显示名称来显示相同​​的信息。

【讨论】:

  • 是的,有道理。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-08-18
  • 2020-07-23
  • 1970-01-01
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
相关资源
最近更新 更多