首页 > 解决方案 > R中的标签分组条形图

问题描述

我正在尝试将标签添加到 r 中的分组条形图。但是我在 y 轴上使用百分比,我希望标签是计数的。我尝试使用 geom_text() 函数,但我不知道我需要使用的参数有多精确。


newdf3 %>%
  dplyr::count(key, value) %>%
  dplyr::group_by(key) %>%
  dplyr::mutate(p = n / sum(n)) %>%
  ggplot() + 
  geom_bar(
    mapping = aes(x = key, y = p, fill = value),
    stat = "identity",
    position = position_dodge()
  ) + 
  scale_y_continuous(labels = scales::percent_format(),limits=c(0,1))+
  labs(x = "", y = "%",title="")+ 
  scale_fill_manual(values = c('Before' = "deepskyblue", 'During' = "indianred1", 'After' = "green2", '?'= "mediumorchid3"),
                    drop = FALSE, name="")

情节1

这是我需要它的一个例子:

情节2

这是我正在使用的数据示例:

key   value

A     Before
A     After
A     During
B     Before
B     Before
C     After
D     During
...

我还想保留没有价值的酒吧(标签= 0)。

有人可以帮我弄这个吗?

标签: rggplot2

解决方案


这是如何将计数标签添加到简单条形图的MWE 。有关将这些分组的情况,请参见下文。

library(datasets)
library(tidyverse)

data <- chickwts %>% 
          group_by(feed) %>% 
          count %>% 
          ungroup %>% 
          mutate(p = n / sum(n))

ggplot(data, aes(x = feed, y = p, fill = feed)) + 
  geom_bar(stat = "identity") + 
  geom_text(stat = "identity",
            aes(label = n), vjust = -1)

带标签的条形图。

你应该能够对你的数据做同样的事情。

编辑: StupidWolf 在评论中指出原始示例已分组数据。添加与此position = position_dodge(0.9)geom_text交易。

同样,无法访问原始数据,但这里有一个不同的 MWE 使用mtcars显示:

library(datasets)
library(tidyverse)

data <- mtcars %>% 
  as_tibble %>% 
  transmute(gear = as_factor(gear), 
            carb = as_factor(carb), 
            cyl = cyl) %>% 
  group_by(gear, carb) %>% 
  count

ggplot(data, aes(x = gear, y = n, fill = carb)) +
  geom_bar(stat = "identity", 
           position = "dodge") +
  geom_text(aes(label = n),
            stat = "identity",
            vjust = -1,
            position = position_dodge(0.9))

带有组标签的条形图。


推荐阅读