下面您可以看到金字塔人口图的示例。该图是用 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 ,但使用 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')))
输出:
关于r - Plotly 中的金字塔图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72318377/