[In 3 lines] Plot the population pyramid (bar graph of age group / gender) with Pandas alone

manner

(ax0, ax1), = pd.cut(df['Age'], range(0, 101, 5), right=False).groupby(df['Sex']).value_counts().unstack(0).plot.barh(subplots=True, layout=(1, 2), sharex=False)
ax0.invert_xaxis()
ax1.set_yticklabels([])

image.png

Commentary

df ['Age'] contains age and df ['Sex'] contains gender. The method chain on the first line is decomposed as follows.

((ax0, ax1), = # [[Axes, Axes]]like(1, 2)Will be returned, so unpack and receive
 pd.cut(titanic['Age'], range(0, 101, 5), right=False) #Make it an age group every 5 years
 .groupby(titanic['Sex']) #Grouping by gender
 .value_counts() #Count by gender / age group
 .unstack(0) #Make a procession of age group x gender
 .plot.barh(subplots=True, layout=(1, 2), sharex=False)) #Draw horizontal bar graphs side by side by gender

The graph on the left is flipped horizontally on the second line.

ax0.invert_xaxis() #Flip horizontal

The third line erases the Y-axis scale in the graph on the right.

ax1.set_yticklabels([]) #Turn off the Y-axis scale

the end

It was impossible with one line.

Recommended Posts

[In 3 lines] Plot the population pyramid (bar graph of age group / gender) with Pandas alone
Reformat the timeline of the pandas time series plot with matplotlib
Read the coordinates of the plot on the graph with Python-matplotlib (super beginner)
Create an age group with pandas
Graph the change in the number of keyword appearances per month using pandas
I made a mistake in fetching the hierarchy with MultiIndex of pandas
Bar graph display in pandas (basic edition)
Plot the Nikkei Stock Average with pandas
Match the distribution of each group in Python
The basis of graph theory with matplotlib animation
Make progress of dd visible in the progress bar
[Python] Representing the number of complaints from life insurance companies in a bar graph