如何制作具有更改颜色和多个子图的分组水平条形图

问题描述 投票:0回答:1

在 Python 中,我想制作一个包含三个子图的水平条形图,其中每个面板有五组四个条形图,同时还更改条形图的自动颜色。

基于受此处指南启发的以下代码,我如何才能 a) 更改每组中条形的颜色(例如,更改为深蓝色、浅蓝色、深紫色、浅紫色),以及 b) 制作一个具有三个面板的图,而不仅仅是一个(例如,它可以与我通常用于多个子图的代码结合使用吗?

fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
?

`speed = [40, 48, 52, 69, 88]
lifespan = [70, 1.5, 25, 12, 28]
height = [35, 5, 18, 17, 43]
width = [40, 18, 35, 37, 15]
index = ['elephant', 'rabbit', 'giraffe', 'coyote', 'horse']
df = pd.DataFrame({'speed': speed, 'lifespan': lifespan, 'height': height, 'width': width}, index=index)
ax = df.plot.barh()`
python matplotlib colors bar-chart subplot
1个回答
0
投票

您可以使用 {column_name:color_code} 的字典在

df.plot.barh()
中定义颜色,

ax = df.plot.barh(color={"speed": "#08519c", "lifespan": "#6baed6","height":'#54278f',"width":'#bcbddc'})

或颜色列表,

ax = df.plot.barh(color=["#08519c", "#6baed6",'#54278f','#bcbddc'])

对于多个面板,将图分配给不同的轴,例如,

fig, axes = plt.subplots(1, 3)
for i in range(3):
    df_subset = ...
    axes[i] = df_subset.plot.barh(color={"speed": "#08519c", "lifespan": "#6baed6","height":'#54278f',"width":'#bcbddc'})
© www.soinside.com 2019 - 2024. All rights reserved.