2
votes

I'm using plotly express and the gapminder dataset to plot a bar chart, to which I have some similar dataset. I found the instructions in their official website and here is the code and figure:

import plotly.express as px

gapminder = px.data.gapminder()

fig = px.bar(gapminder, x="continent", y="pop", color="continent",
  animation_frame="year", animation_group="country", range_y=[0,4000000000])
fig.show()

enter image description here

However, I also wish to add another dataset for each bar as a comparison. Ideally, I wish to have a result as below: enter image description here

For the result in each bar, I have a dataset as the "total number". For example, for the first bar, the "yellow one" is the total number and "blue one" is the targeted number, just I wish to combine them in the same figure. But the example only shows a single dataset. I wonder how I can change the parameter of "y" to include the two datasets?

1
I need help... :(Alice jinx
can you put some synthetic data as your additional data ? basically you have to merge data and set a column as an indicator. Then add it as a new trace to your layout.Areza

1 Answers

2
votes

If, as you say, you've got a similar dataset, then you don't need to change the parameter of y to include two datasets. You only have to add another dimension to your existing dataset and adjust how you're using the x and color arguments. In your example you're assigning continent to both x and color. So you're indicating the different continents in two ways. And you don't have to do that. You can use color to split two datasets and still keep the population data illustrated on different contintents. I'll show you how to do that.


Gapminder has data for all five continents. The following snippets adds the gapminder data to itself, and uses a new column planet to split the combined dataset in two. This way you'll sort of have two planets with the same continents. This will work perfectly fine as long as you have the same continents for both planets.

Plot:

enter image description here

Code:

import plotly.express as px
import pandas as pd

gapminder = px.data.gapminder()
gapminder2=gapminder.copy(deep=True)

gapminder['planet']='earth'
gapminder2['planet']='mars'
gapminder3=pd.concat([gapminder, gapminder2])

fig = px.bar(gapminder3, x="continent", y="pop", color="planet",
  animation_frame="year", animation_group="country", range_y=[0,4000000000*2])
fig.show()