Color Customization Population Pyramid in R
To customize the color of male and female bars, we use the fill aesthetic property of the ggplot() function. We can either pass the variable according to which we want the colors to be or we can pass the exact colors that need to be put. We can even use the scale_fill_brewer() function to set the color to a predefined palette.
Syntax:
ggplot( df, aes(x, y, fill) )
Parameters:
- fill: determines the variable according to which bars are to be colored.
Example:
Here, in this example wh have colored the plot in sequential palette number 7.
R
# load sample data sample_data <- read.csv ( "Population.CSV" ) # load library ggplot2 and dplyr library (ggplot2) library (dplyr) # change male population to negative sample_data %>% mutate ( population = ifelse (gender== "M" , population*(-1), population*1))%>% ggplot ( aes (x = age,y = population, fill=gender)) + geom_bar (stat = "identity" ) + coord_flip ()+ scale_fill_brewer (type = "seq" ,palette = 7) |
Output:
How to Create a Population Pyramid in R?
In this article, we will discuss how to create a population pyramid in the R Programming Language.
A population pyramid is also known as an age-sex pyramid. It helps us to visualize the distribution of a population by age group and sex. It generally takes the shape of a pyramid. In the population pyramid, males are usually depicted on the left and females on the right. This method of data visualization can be used to visualize the age of a particular population based on the number or percentage of male and female inhabitants.
To create a population pyramid in the R Language, we use the geom_bar() function of the ggplot2 package. The ggplot2 is a system for declaratively creating graphics, based on “The Grammar of Graphics”. The geom_bar() function is used to draw the bar plots, it makes the height of the bar proportional to the number of cases in each group.