Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中标记分组条形图_R_Ggplot2 - Fatal编程技术网

在R中标记分组条形图

在R中标记分组条形图,r,ggplot2,R,Ggplot2,我正在尝试将标签添加到r中的分组条形图中。 但是,我在y轴上使用percentege,我希望标签是count。 我尝试过使用geom_text()函数,但不知道需要使用的参数有多精确 newdf3 %>% dplyr::count(key, value) %>% dplyr::group_by(key) %>% dplyr::mutate(p = n / sum(n)) %>% ggplot() + geom_bar( mapping =

我正在尝试将标签添加到r中的分组条形图中。 但是,我在y轴上使用percentege,我希望标签是count。 我尝试过使用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="")

以下是我如何需要它的一个示例:

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

key   value

A     Before
A     After
A     During
B     Before
B     Before
C     After
D     During
...
我还想保留没有值的条(label=0)

有人能帮我吗?

以下是如何将计数标签添加到简单的条形图中。请参见下文,了解分组时的情况

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)

这个问题显示了一个并排的条形图,因此可能会更复杂一些。我想应该提供数据集。你说得对,谢谢你指出这一点。请参阅编辑,它可能更紧密地反映OP的用例。正如您所说,如果没有原始数据,很难准确地模拟它。您是否可以尝试使用dput来提供数据集,这有点不寻常,而且由于位置闪避,添加标签可能有点棘手
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))