【问题标题】:Plotly stacked horizontal bar chart as percentages in R将堆积的水平条形图绘制为R中的百分比
【发布时间】:2020-10-24 13:38:36
【问题描述】:

假设我有一个数据集,其中包含每个城镇的男性和女性百分比以及城镇组(假设是州):

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)

我想做的是使用 Plotly 包生成一个堆叠的水平条形图,这样我将有 2 个条(每个州一个)以及这些条中每种性别的平均百分比。平均男性和女性的总和应为 100%。 我知道我必须转换我拥有的数据,也许使用 group_by 状态,但我不知道具体如何。

提前致谢!

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    我认为您可能打算这样设置数据框:

    df <- data.frame(town = town, females = females, males = males, state = factor(state))
    

    而不是使用c(),它将创建一个向量。

    可以使用dplyr 中的pivot_longer 重新调整数据,这样您就有一个单独的性别和百分比列(在每个城镇和州内)。

    然后,您可以通过按stategender 分组来计算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"
      )
    

    情节

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-27
      • 2019-06-08
      • 2021-12-22
      • 1970-01-01
      • 2019-11-25
      • 2018-03-15
      • 1970-01-01
      • 2021-05-31
      相关资源
      最近更新 更多