简体   繁体   中英

Plotly Express - ho to plot a stacked bar chart of single variable

I have a dataframe like this

df = pd.DataFrame({'name':['a', 'b', 'c', 'd', 'e'], 'value':[54.2, 53.239, 43.352, 36.442, -12.487]})
df

I'd like to plot a simple stacked bar chart like the one below whit plotly.express

在此处输入图像描述

How can a I do that? I've seen on documentation several examples but none of them solved my problem Thank you

The bar chart's only ever going to have one column? That seems like an odd use-case for a bar chart, but...

What I would do is create one trace per "name", filtering df as trace_df=df[df['name']==name], and then make a Bar for each of those, something like this:

import plotly.graph_objects as go

trace_dfs = [df[df['name']==name] for name in df['name']]
bars = [
    go.Bar(
        name=name,
        x=['constant' for _ in trace_frame['value']],
        y=trace_frame['value'],
    )
    for trace_frame in trace_dfs
]
fig = go.Figure(
    data=bars,
    barmode='stack'
)

Granted, that's not plotly_express , it's core plotly , which allows a lot more control. If you want multiple stacked bars for different values, you'll need separate labels and separate values for x and y, not the two-column DF you described. There are several more examples here and a full description of the available bar chart options here .

It's a little wordy, but you can set a single value for the x axis, in this case zero. Then you just need to tweak your dimension, lables, and ranges.

import pandas as pd
import plotly.express as px
df = pd.DataFrame({'name':['a', 'b', 'c', 'd', 'e'], 'value':[54.2, 53.239, 43.352, 36.442, -12.487]})


df['x'] = 0

fig = px.bar(df, x='x', y='value',color='name', width=500, height=1000)

fig.update_xaxes(showticklabels=False, title=None)
fig.update_yaxes(range=[-50,200])
fig.update_traces(width=.3)
fig.show()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM