Here is an example of a Pyramid population plot (aka population pyramid), prepared with ggplot2 as follows:
library(ggplot2)
set.seed(1)
#create data frame
data <- data.frame(age = rep(1:100, 2), gender = rep(c("M", "F"), each = 100))
#add population variable
data$population <- 1/sqrt(data$age) * runif(200, 10000, 15000)
ggplot(data, aes(x = age, fill = gender,
y = ifelse(test = gender == "M",
yes = -population, no = population))) +
geom_bar(stat = "identity") +
scale_y_continuous(labels = abs, limits = max(data$population) * c(-1,1)) +
labs(title = "Population Pyramid", x = "Age", y = "Percent of population") +
coord_flip()

So now I want to do the same plot but with a Plotly package. I don't like to use ggplotly command and I tried to follow some examples but it is not working:
plot_ly(data, x = population, y = age, group = gender, type = 'bar', orientation = 'h',
hoverinfo = 'y+text+name', text = abs_pop) %>%
layout(bargap = 0.1, barmode = 'overlay',
xaxis = list(tickmode = 'array', tickvals = c(-1000, -500, 0, 500, 1000),
ticktext = c('1000', '500', '0', '500', '1000')))
How do I make this plot with Plotly?
You can use the following code:
library(plotly)
library(dplyr)
data %>%
mutate(population = ifelse(test = gender == "M", yes = -population, no = population)) %>%
mutate(abs_pop = abs(population)) %>%
plot_ly(x= ~population, y=~age, color=~gender) %>%
add_bars(orientation = 'h', hoverinfo = 'text', text = ~abs_pop) %>%
layout(bargap = 0.1, barmode = 'overlay',
xaxis = list(tickmode = 'array', tickvals = c(-15000, -10000, -5000, 0, 5000, 10000, 15000),
ticktext = c('15000', '10000', '5000', '0', '5000', '10000', '15000')))
Output:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With