Plotly 中的金字塔图

Pyramid plot in Plotly

下面是金字塔人口图的示例。这个图是用 ggplot2 准备的,你可以在下面看到这个图。

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()

所以现在我想用 Plotly 包做同样的情节。我不喜欢使用 ggplotly 命令,我尝试遵循一些示例但没有用:

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')))

谁能帮我解决这个问题并用 Plotly 制作这个情节。

您可以使用以下代码:

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')))

输出: