Change bar colors in grouped bar plot built in a loop

112 Views Asked by At

How can I change the colors of the bars in the bar plot?

species = ("Adelie", "Chinstrap", "Gentoo")
penguin_means = {
    'Bill Depth': (18.35, 18.43, 14.98),
    'Bill Length': (38.79, 48.83, 47.50),
    'Flipper Length': (189.95, 195.82, 217.19),
}

x = np.arange(len(species))  # the label locations
width = 0.25  # the width of the bars
multiplier = 0

fig, ax = plt.subplots(layout='constrained')

for attribute, measurement in penguin_means.items():
    offset = width * multiplier
    rects = ax.bar(x + offset, measurement, width, label=attribute)
    ax.bar_label(rects, padding=3)
    multiplier += 1

ax.set_ylabel('Length (mm)')
ax.set_title('Penguin attributes by species')
ax.set_xticks(x + width, species)
ax.legend(loc='upper left', ncols=3)
ax.set_ylim(0, 250)

plt.show()`

Expected:

I want to change the bar colors to : color = ['lightsalmon', 'lightseagreen', 'darkseagreen', 'mediumorchid']

1

There are 1 best solutions below

0
On
  • The following implementation updates the existing code.
  • Use zip to combine colors to penguin_means.items() and iterate through them, which allows for use of the color parameter in ax.bar.
species = ("Adelie", "Chinstrap", "Gentoo")
penguin_means = {
    'Bill Depth': (18.35, 18.43, 14.98),
    'Bill Length': (38.79, 48.83, 47.50),
    'Flipper Length': (189.95, 195.82, 217.19),
}

colors = ['lightsalmon', 'lightseagreen', 'darkseagreen', 'mediumorchid']

x = np.arange(len(species))  # the label locations
width = 0.25  # the width of the bars
multiplier = 0

fig, ax = plt.subplots(layout='constrained')

# update here with zip and color
for color, (attribute, measurement) in zip(colors, penguin_means.items()):
    offset = width * multiplier

    # update here by adding the color parameter
    rects = ax.bar(x + offset, measurement, width, label=attribute, color=color)  # update here
    ax.bar_label(rects, padding=3)
    multiplier += 1

ax.set_ylabel('Length (mm)')
ax.set_title('Penguin attributes by species')
ax.set_xticks(x + width, species)
ax.legend(loc='upper left', ncols=3)
ax.set_ylim(0, 250)

plt.show()

  • Implement the same functionality in a more streamlined methology.
  • Use pandas to create a pands.DataFrame and pandas.DataFrame.plot to more easily create grouped bars.
    • The index values will be on the independent axis, and bars are created with the specified color for each column.
import pandas as pd

# create a dataframe
df = pd.DataFrame(data=penguin_means, index=species)

# plot
ax = df.plot(kind='bar', color=colors, rot=0, figsize=(7.5, 5), ylim=(0, 250),
             width=0.85, title='Penguin Species Addributes', ylabel='Length (mm)')

# add the bar labels
for c in ax.containers:
    ax.bar_label(c, padding=3)

# move the legend
_ = ax.legend(loc='upper left', ncols=3)

enter image description here Plot generated by both implementations.

df

           Bill Depth  Bill Length  Flipper Length
Adelie          18.35        38.79          189.95
Chinstrap       18.43        48.83          195.82
Gentoo          14.98        47.50          217.19