如何使用ggplot2在条形图上放置标签?

How to put label on bar plot using ggplot2?

我是 r 的初学者,我在这里遇到了两个问题。如果有人能帮助我,我将不胜感激。

  1. 我的代码没有在条形图中显示正确的分布,我做错了什么? (我试图显示基于性别和 class 的存活率)
  2. 如何在每个栏的顶部显示每个标签的值?

这是我的代码:

library(ggplot)

ds <- as.data.frame(Titanic)
color_survived = "#FFA500"
color_dead = "#0000FF"

ds$Sex <- as.factor(ds$Sex)

ds$Survived <- as.factor(ds$Survived)

categorical.ds <- ds  %>%
  select(Sex,
         Class,
         Survived) %>%
  gather(key = "key", value = "value", -Survived)

categorical.ds %>% 
  ggplot(ds ,aes(value)) +
  geom_bar(aes(x        = value, 
               fill     = Survived), 
               alpha    = .2, 
               position = "dodge", 
               color    = "black",
               width    = .7) +
  labs(x = "",
       y = "") +
  theme(
    axis.text.y  = element_blank(),
    axis.ticks.y = element_blank()) +
  facet_wrap(~ key, scales = "free", nrow = 1) +
  scale_fill_manual(values = c(color_survived, color_dead), name   = "Survived", labels = c("Survived", "Dead"))

剧情如下:

非常感谢!

这里有一些东西,希望对您有所帮助!

长话短说:

  • 如果你想要的只是幸存者率,我认为你做的事情太复杂了,不需要使用gather(如果你真的想要,更推荐pivot_longer)。我改用了 group_bysummarize,这是聚合所需要的。
  • 因为两张图的x不一样,所以做两张图比较简单,一张给class,一张给性。然后将它们与 + 组合,加载 patchwork
  • 注意,geom_col 是你想要的,geom_bar 是密谋计数
  • 关于您的标签问题,只需使用geom_text

欢迎加入 R 社区!

##we need the tidyverse package for data manipulation and ggplot
library(tidyverse)
##since we'll make 2 different graphs, patchwork will allow us to combine them
library(patchwork)

#data reproduction
ds <- data.frame(Sex = sample(c("male", "female"), size = 100, replace = TRUE),
                 Survived = sample(c("survived", "dead"), size = 100, replace = TRUE),
                 Class = sample(c("1st", "2nd", "3rd", "crew"), size = 100, replace = TRUE))

#I start with classes : group_by allows us to compute the rate of each group
#summarize uses these group to compute the rate : number of survivors / number in the group (and not NA)
class.ds <-  ds  %>%
  select(Class, Survived) %>%
    group_by(Class) %>%
    summarize(surv_rate = sum(Survived == "survived") / sum(!is.na(Survived)))

#we do the same for the sex
sex.ds <- ds  %>%
  select(Sex, Survived) %>%
  group_by(Sex) %>%
  summarize(surv_rate = sum(Survived == "survived") / sum(!is.na(Survived)))

#now the plots : class is our x axis, the rate is the y axis.
#geom_col is used for the bars, geom_text is for the labels
#of course, you can then add color etc, here I keep it simple
class.plot <- class.ds %>% ggplot(aes(Class, surv_rate)) +
  geom_col() +
  geom_text(aes(label = round(surv_rate, 2)), nudge_y = 0.02)

#same thing for the sex
sex.plot <- sex.ds %>% ggplot(aes(Sex, surv_rate)) +
  geom_col() +
  geom_text(aes(label = round(surv_rate, 2)), nudge_y = 0.02)

#now we just need to group the graphs with patchowork
class.plot + sex.plot