Plotly: How to make stacked bar chart from single trace?

2024/9/29 5:23:27

Is it possible to have two stacked bar charts side by side each of them coming from a single column?

Here's my df:

Field       IssuePolice      Budget cuts
Research    Budget cuts
Police      Time consuming
Banking     Lack of support
Healthcare  Lack of support
Research    Bureaucracy
Healthcare  Bureaucracy
Banking     Budget cuts

I want a stacked bar chart of Field next to a stacked bar chart of issues by field.

Thanks guys!

Answer

For an example on how to make a stacked bar chart with the specific dataset provided, take a look at the suggestion in Plotly-Dash: Want two stacked bar charts side by side from single df column. The following answer addresses how you can not make a stacked bar chart with a single trace. To show you why, I'll start with what may seem like redundant details. But hopefully everything will be clear in the end.


In plotly terms, trace is used to describe a graph object such as Scatter or Bar like in the snippet below.

Snippet 1.1:

import plotly.graph_objs as go
fig = go.Figure(go.Bar(x=['CategoryA', 'CategoryB', 'CategoryC'],y=[20, 14, 23]))
fig.update_layout(template = 'plotly_dark').show()

If you look at the snippet above, you'll see that that is a bar chart with a single trace in the form of go.Bar(x=['CategoryA',....

Plot 1.1:

enter image description here

Now, how can we add something to make it a stacked chart? If you start out by adding an element to x like 'CategoryD', then nothing happens. And that's a bit interesting since you'd might expect an error message instead.

Plot 1.2: Added x value

enter image description here

Snippet 1.2

import plotly.graph_objs as go
fig = go.Figure(go.Bar(x=['CategoryA', 'CategoryB', 'CategoryC', 'CategoryD'],y=[20, 14, 23]))
fig.update_layout(template = 'plotly_dark').show()

But nothing happens before CategoryD has a corresponding y value like 15:

Plot 1.3: Added x and y value

Conclusion so far: Adding values to x and y will add another category on the x-axis and a value on the y-axis. As you can see, nothing is getting stacked here quite yet:

enter image description here

Snippet 1.3:

import plotly.graph_objs as go
fig = go.Figure(go.Bar(x=['CategoryA', 'CategoryB', 'CategoryC', 'CategoryD'],y=[20, 14, 23, 15]))
fig.update_layout(template = 'plotly_dark').show()

But what if you add a layout term with barmode='stack'?


Snippet 2:

import plotly.graph_objs as gofig = go.Figure(go.Bar(x=['CategoryA', 'CategoryB', 'CategoryC', 'CategoryD'],y=[20, 14, 23, 15]))fig.update_layout(barmode='stack',title = 'Stacked bar chart',template = 'plotly_dark').show()

Plot 2: barmode='stack'

enter image description here

I can understand anyone hoping that this would stack all data within a single trace, but plotly just isn't built that way. To get what you need, you'll have to add another trace using fig.add_trace(go.Bar()) or simply fig.add_bar().

Snippet 3:

import plotly.graph_objs as go
fig = go.Figure(go.Bar(x=['CategoryA', 'CategoryB', 'CategoryC', 'CategoryD'],y=[20, 14, 23, 15]))
fig.add_bar(x=['CategoryA', 'CategoryB', 'CategoryC', 'CategoryD'],y=[5, 14, 4, 20])
fig.update_layout(barmode='stack',title = 'Stacked bar chart!',template = 'plotly_dark').show()

Plot 3: Add trace

enter image description here

Notice that neither of the go.Bar() objects have had any name assigned to them, and that plotly by default names them trace 0 and trace 1. So I guess it's more correct to say that a trace contains or 'shows' a plotly graph object rather than calling them the same thing. If you'd like to specify other names, you can do so with, for example, name = 'segment 1' like this:

Snippet 4:

import plotly.graph_objs as go
fig = go.Figure(go.Bar(x=['CategoryA', 'CategoryB', 'CategoryC', 'CategoryD'],y=[20, 14, 23, 15],name = 'segment 1'))
fig.add_bar(x=['CategoryA', 'CategoryB', 'CategoryC', 'CategoryD'],y=[5, 14, 4, 20],name = 'segment 2')
fig.update_layout(barmode='stack',title = 'Stacked bar chart!',template = 'plotly_dark').show()

Plot 4: Add named traces

enter image description here

If you'd like to 'unstack' your bars, just change barmode to 'group' like this:

fig.update_layout(barmode='group'),

Plot 5:

enter image description here

https://en.xdnf.cn/q/71253.html

Related Q&A

zip function help with tuples

I am hoping someone can help me with a problem Im stuck with. I have a large number of tuples (>500) that look like this:(2,1,3,6) (1,2,5,5) (3,0,1,6) (10,1,1,4) (0,3,3,0) A snippet of my c…

Mini batch training for inputs of variable sizes

I have a list of LongTensors, and another list of labels. Im new to PyTorch and RNNs so Im quite confused as to how to implement minibatch training for the data I have. There is much more to this data,…

Python gTTS, is there a way to change the speed of the speech

It seems that on gTTS there is no option for changing the speech of the text-to-speech apart from the slow argument. I would like to speed up the sound by 5%. Any suggestion on how I can do it? Best.t…

Change QLabel text dynamically in PyQt4

My question is: how can I change the text in a label? The label is inside a layout, but setText() does not seem to work - maybe I am not doing it right. Here is my code:this is the Main windows GUI, t…

Setting figure size to be larger than screen size in matplotlib

Im trying to create figures in matplotlib that read nicely in a journal article. I have some larger figures (with subfigures) that Id like to take up nearly an entire page in portrait mode (specificall…

Tensorflow 0.7.1 with Cuda Toolkit 7.5 and cuDNN 7.0

I recently tried to upgrade my Tensorflow installation from 0.6 to 0.7.1 (Ubuntu 15.10, Python 2.7) because it is described to be compatible with more up-to-date Cuda libraries. Everything works well i…

How to export tensor board data?

In the tensorborads README.md, it ask me to do like this:How can I export data from TensorBoard?If youd like to export data to visualize elsewhere (e.g. iPython Notebook), thats possible too. You can…

Releasing Python GIL while in C++ code

Ive got a library written in C++ which I wrap using SWIG and use in python. Generally there is one class with few methods. The problem is that calling these methods may be time consuming - they may han…

How to include the default TEMPLATE_CONTEXT_PROCESSORS in the new TEMPLATES setting in Django 1.10

Im upgrading a project to Django 1.10 and it has code like the following:from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCPTEMPLATE_CONTEXT_PROCESSORS = TCP + (django.template.c…

Selecting best range of values from histogram curve

Scenario :I am trying to track two different colored objects. At the beginning, user is prompted to hold the first colored object (say, may be a RED) at a particular position in front of camera (marked…