[英]Plotly stacked horizontal bar chart as percentages in R
Let's say I have a dataset with percentages of males and females in each town, and groups of towns (let's say states):假设我有一个数据集,其中包含每个城镇和城镇组(比方说州)的男性和女性百分比:
town <- 1:4
females <- c(64.5, 86.3, 35.7, 45.6)
males <- 100 - females
state <- c(1, 2, 2, 1)
df <- c(town, females, males, state)
What I wanna do is generate a stacked horizontal bar chart using the Plotly package, in a way that I'll have 2 bars (one for each state) and the mean percentages of each gender in these bars.我想做的是使用 Plotly package 生成一个堆叠的水平条形图,我将有 2 个条形图(每个州一个)以及这些条形图中每个性别的平均百分比。 The sum of mean males and females should be 100%.
平均男性和女性的总和应为 100%。 I'm aware I'll have to transform the data I have, maybe use a group_by state, but I don't know exactly how.
我知道我必须转换我拥有的数据,也许使用 group_by state,但我不知道具体怎么做。
Thanks in advance!提前致谢!
I think you may have intended to set up your data frame like this:我认为您可能打算像这样设置数据框:
df <- data.frame(town = town, females = females, males = males, state = factor(state))
instead of using c()
which will create a vector.而不是使用将创建向量的
c()
。
Reshaping data could be done, using pivot_longer
from dplyr
so that you have a separate column for gender and percentage (within each town and state).可以使用
pivot_longer
中的dplyr
来重塑数据,这样你就有了一个单独的性别和百分比列(在每个城镇和州内)。
Then, you can compute the percentage_mean
by grouping by state
and gender
.然后,您可以通过按
state
和gender
分组来计算percentage_mean
。
library(tidyverse)
library(plotly)
df %>%
pivot_longer(cols = c(females, males), names_to = "gender", values_to = "percentage") %>%
group_by(state, gender) %>%
summarise(percentage_mean = mean(percentage)) %>%
plot_ly(
x = ~percentage_mean,
y = ~state,
color = ~gender,
type = "bar",
orientation = "h"
) %>%
layout(
barmode = "stack"
)
Plot Plot
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.