matplotlib 更改在循环中构建的分组条形图中的条形颜色

z9ju0rcb  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(106)

如何更改条形图中条形的颜色?

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

字符串
预期:
我想将条形图的颜色更改为:color = ['lightsalmon', 'lightseagreen', 'darkseagreen', 'mediumorchid']

uqdfh47h

uqdfh47h1#

  • 使用zip将合并colorspenguin_means.items()合并,并在它们之间切换,这允许在ax.bar中使用color参数。
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()

字符串

  • 使用pandas创建pands.DataFramepandas.DataFrame.plot更容易地创建分组条形图。
  • 索引值将位于独立的轴上,并且为每列创建具有指定颜色的条形图。
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)


的数据

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

相关问题