r - Plotly 中的金字塔图

标签 r ggplot2 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()

enter image description here

所以现在我想做同样的 plotly ,但使用 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')))

输出:

enter image description here

关于r - Plotly 中的金字塔图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72318377/

相关文章:

javascript - 更改plotly js中的z索引标签

python - 将控制过滤器添加到 Plotly 条形图中

r - 将 NA 引入 as.numeric

r - 用 R 分析时间序列

python - 时间序列中每秒、每小时、每天的请求数

r - 使用 ggplot 将条形图的列与线图的点对齐

r - scale_y_reverse() 在 ggplot2 中不起作用

r - 如何将计算列添加到其他数据框的一系列联接中间的数据框?

r - 如何使用 ggmap 绘制带孔的 shp?

javascript - 如何在 plotly 中为形状添加名称或标签?