【问题标题】:Change geom_bar to percentages instead of count将 geom_bar 更改为百分比而不是计数
【发布时间】:2020-11-30 18:35:45
【问题描述】:

我正在使用 ggplot 制作带有条形图的交互式时间序列,然后将其转换为 plotly。每个条形代表一年 16,17 和 18 (data_long.edad),我根据职业 (data_long.ocup) 为它们着色。 我的图表显示 count,但我希望能够显示 每个条形的百分比(每个条形加起来应该是 100%) 我尝试了很多方法,但都失败了。 我的问题与ggplot replace count with percentage in geom_bar 这个问题非常相似,但我无法使该解决方案发挥作用。我无法转换我的数据(可能是因为在我的情况下我有因子变量?)。

有什么想法吗?

>   head(df,20)
    data_long.edad         data_long.ocup
1             a16r        Oc. de limpieza
2             a18r         Aún no ingesa al ML
3             a18r       Aún no ingesa al ML
4             a17r   Aún no ingesa al ML
5             a17r   Aún no ingesa al ML
6             a16r  Oficiales y operarios
7             a17r   Aún no ingesa al ML
8             a17r   Aún no ingesa al ML
9             a17r   Trab. de los servicios
10            a16r    Aún no ingesa al ML
11            a16r Trab. de los servicios
12            a16r    Aún no ingesa al ML
13            a18r       Administrativos
14            a18r       Oficiales y operarios
15            a16r      Trab. calificados
16            a18r       Aún no ingesa al ML
17            a18r       Aún no ingesa al ML
18            a18r       Aún no ingesa al ML
19            a16r  Oficiales y operarios
20            a16r    Aún no ingesa al ML




  gocup <-  ggplot(df, aes(x=data_long.edad)) +
    geom_bar(aes(fill=factor(data_long.ocup))) +
    ggtitle("Trayectorias ocupacionales") 
  
  gocup
  
  rm (ocuint)
  ocupint = ggplotly(p= gocup, tooltip= c("x", "y")) %>%
    style(hoverlabel = labels) %>%
    layout(font = TRUE,
           yaxis = list(fixedrange = TRUE),
           showlegend = TRUE,
           legend=list(title=list(text='<b> Ocupación </b>')),
           xaxis = list(fixedrange = TRUE)) %>%
    config(displayModeBar = FALSE)
  
  ocupint 

我的图表看起来像这样,而不是计数,我想要百分比,每个条形都上升到 100。 (这张图比我提供的数据示例显示了更多的年份和更多的职业,但数据结构相同)

【问题讨论】:

    标签: r ggplot2 plotly geom-bar


    【解决方案1】:

    您可以在geom_bar() 调用中使用position = "fill"。这会将所有内容填充到 100%:

    # From some random data
    tibble(a = sample(letters[1:10], 5000, replace = TRUE),
           b = sample(LETTERS[1:10], 5000, replace = TRUE)) %>% 
      ggplot(aes(a, fill = b)) +
      geom_bar(position = "fill") +
      scale_y_continuous(name = "percent",
                         breaks = c(0, 0.5, 1), 
                         labels = scales::percent(c(0, 0.5, 1))) 
    

    这使用了其他解决方案中的一些符号来计算百分比:

    【讨论】:

    • 安德鲁是正确的。您还可以在 scale_y_continuous 函数中包含 name="Percent" 以将工作“count”更改为“Percent”。
    • 好发现 - 懒我!
    猜你喜欢
    • 2018-03-17
    • 2014-09-06
    • 2021-11-05
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    相关资源
    最近更新 更多