在Python中更改条形图的颜色

时间:2017-08-15 20:03:27

标签: python pandas histogram

我有三组按组显示的直方图。在此设置中,我想按颜色enter image description here区分每个组。

例如,隔间 - 红色,走廊 - 蓝色,办公室 - 绿色。有什么建议吗?

这是我目前的代码:

df_mean['mean'].hist(by=df_mean['type'])

2 个答案:

答案 0 :(得分:0)

您是否尝试将颜色参数传递给hist?

plt.hist(x, color='r')

答案 1 :(得分:0)

在使用 df.hist() 创建图形后,您可以为每个直方图设置颜色,如下例所示:

import numpy as np                 # v 1.19.2
import pandas as pd                # v 1.1.3
import matplotlib.pyplot as plt    # v 3.3.2

# Create random dataset
rng = np.random.default_rng(seed=12345) # random number generator
df = pd.DataFrame(dict(area_type = np.repeat(['cubicle', 'hallway', 'office'], [9, 10, 12]),
                       mean = np.append(rng.uniform(low=100, high=1400, size=9),
                                        rng.exponential(scale=500, size=22))))

# Plot grid of histograms using pandas df.hist (note that df.plot.hist
# does not produce the same result, it seems to ignore the 'by' parameter)
grid = df['mean'].hist(by=df['area_type'])
colors = ['red', 'blue', 'green']

# Loop through axes contained in grid and list of colors
for ax, color in zip(grid.flatten(), colors):
    # Loop through rectangle patches representing the histogram contained in ax
    for patch in ax.patches:
        patch.set_color(color)

# Change size of figure
plt.gcf().set_size_inches(8, 6)

plt.show()

pandas_hist_color1

除了手动选择颜色之外,您还可以从所选的 colormap 中自动选择颜色(在这种情况下,定性颜色图是合适的),如下所示:

# Select colormap properties
cmap_name = 'Accent' # enter any colormap name (see whole list by running plt.colormaps())
ncolors = df['area_type'].nunique()

# Extract list of colors that span the entire gradient of the colormap
cmap = plt.cm.get_cmap(cmap_name)
colors = cmap(np.linspace(0, 1, ncolors))

# Create plot like in previous example
grid = df['mean'].hist(by=df['area_type'])
for ax, color in zip(grid.flatten(), colors):
    for patch in ax.patches:
        patch.set_color(color)
plt.gcf().set_size_inches(8, 6)
plt.show()

pandas_hist_color2