按原样分组和堆叠的条形图

Bar plot with plotly grouped and stacked as is

我的输入:

    df=(pd.DataFrame({'label_color':['white','white','cyan','cyan','cyan','cyan','white','white'],
                  'label_quality':['white','white','red','green','green','red','white','white'],
'label':['foo','foo','foo','foo','foo','foo','foo','foo']}))

让我解释一下我想要什么:“一栏”将是 label color,“第二栏”将是 label_quality,其中 x.axisdf.index 并且相关按索引顺序定位列。 y.axis 也只是标签的名称。 colors 是来自 df 列的值["label_colors ","label_quality"]

这里提供的解决方案@r_beginners:

df['color_value'] = 1
df['quality_value'] = 1

fig = px.bar(df, y=['color_value','quality_value'],
             x=[1]*len(df),
             orientation='h',
             barmode='group',
             template='plotly_white')

fig.data[0]['marker']['color'] = df['label_color'].tolist()
fig.data[1]['marker']['color'] = df['label_quality'].tolist()
fig.update_traces(marker_line_color='rgb(8,48,107)')
fig.update_layout(showlegend=False, yaxis_title='foo', xaxis_title='')
fig.show()

但是真实数据看起来有些奇怪:

似乎列边框重叠了:

我找到解决方案:fig.update_traces(marker_line_color='rgb(255,255,255)', marker_line_width=0 )

所以:

希望对需要可视化数据的人有所帮助

您呈现的数据与图表x轴的内容不符,但是为了达到您想要的效果,您需要为每一个数据都加上值,因为不能只用图表来绘制图表颜色名称。此外,在完成水平条形图后,我用所需的颜色更新了列列表。改变边框的颜色以确定相对于颜色它是空白还是白色。根据图表的用途,甘特图可能比时间线更可取。

df['color_value'] = 1
df['quality_value'] = 1

fig = px.bar(df, y=['color_value','quality_value'],
             x=[1]*len(df),
             orientation='h',
             barmode='group',
             template='plotly_white')

fig.data[0]['marker']['color'] = df['label_color'].tolist()
fig.data[1]['marker']['color'] = df['label_quality'].tolist()
fig.update_traces(marker_line_color='rgb(8,48,107)')
fig.update_layout(showlegend=False, yaxis_title='foo', xaxis_title='')
fig.show()