I am freshman in all things Python, pandas and plotly. I am doing a personal project on population of individual countries and I would like to make a plotly.express + dash graph environment, but I have run into trouble already at the beginning. 😀
Initially, I was able to get a nice table through some pivoting and resetting of indices, like here:
Data table
The table has country, sex (male, female, both) and year (1961-2019), followed by population per each age range (5-9, 10-14, …, Total). I know I can “extract” individual country and year with as simple line of code as:
country, year = "Andorra", 2019
df_country = df[ (df["geo"] == country) & (df['TIME_PERIOD'] == year) ]
to get something like this:
Data filtered per country and year
And then I tried to get a px.bar chart based on the upper table, so that I get two horizontal bars (male, female) for each age range in the same graph. I wrote following code:
px.bar(data_frame=df_country, x=df_country.loc[:, '<5':'75<'].columns, color='sex', height=300)
and got this:
Weird stats for Andorra?
So, the bars are divided by sex categories (third one includes ‘male+female’), but rather than having age ranges on the y-axis, each bar as been sliced into a portion which corresponds to numerical values from the table.
I have a feeling it has to do something with those “wide” and “long” data formats, but I could be wrong.
What I would like to get from the upper table is just to select one country (say Andorra), and then that it shows two bars (male, female) per each age range on y-axis. Something like this:
One-bar version.
I’d also like to include the Andorra dataframe in such a way that I can use TIME_PERIOD columnd (which is basically years) for that nice slider which is usually defined by animation_frame
variable.
I suppose the code would look something like:
px.bar(data_frame=df_country, x=df_country.loc[:, '<5':'75<'], color='sex', animation_frame='TIME_PERIOD')
The idea is to, eventually, make a selection of country through dash, but px.bar would generate these ‘male,female per age range’ bars and would have a slider for years. I am avoiding the classical population pyramid for now.
Thanks in advance.
Demenaio is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.