将 geom_bar 更改为百分比而不是计数

Change geom_bar to percentages instead of count

我正在使用 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。 (这张图显示了比我提供的数据示例更多的年份和更多的职业,但数据结构相同)

您可以在 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))) 

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