R语言 ggplot:添加具有不同类别数量的观测数量的标签

gopyfrb3  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(100)

我怎样才能不仅添加一个带有观察数量的标签(这已经在这里很好地描述了),而且还添加不同类的数量,例如:**"*10个观察 * 来自 *3个制造商 *"**到下面图的每个方面?

ggplot(mpg, aes(y=cty)) + 
  geom_boxplot() +
  facet_grid(cols=vars(class))

字符串

(The mpg数据集的前三行如下所示:)

> head(mpg)
# A tibble: 6 × 11
  manufacturer model displ  year   cyl trans      drv     cty   hwy fl    class  
  <chr>        <chr> <dbl> <int> <int> <chr>      <chr> <int> <int> <chr> <chr>  
1 audi         a4      1.8  1999     4 auto(l5)   f        18    29 p     compact
2 audi         a4      1.8  1999     4 manual(m5) f        21    29 p     compact
3 audi         a4      2    2008     4 manual(m6) f        20    31 p     compact

rqdpfwrv

rqdpfwrv1#

library(ggplot2)
library(dplyr)

# Calculate summary statistics for each facet
 mpg_summary <- mpg %>%
  group_by(class) %>%
  summarize(
    n_obs = n(),
    n_models = n_distinct(model),
    n_manufacturers = n_distinct(manufacturer)
  ) %>%
  mutate(
    label = paste0(
      n_obs,
      " observation",
      ifelse(n_obs != 1, "s", ""),  # Pluralize "observation" if more than 1
      " for ",
      n_models,
      " model",
      ifelse(n_models != 1, "s", ""),  # Pluralize "model" if more than 1
      " from ",
      n_manufacturers,
      " manufacturer",
      ifelse(n_manufacturers != 1, "s", "")  # Pluralize "manufacturer" if more than 1
    )
  )

# Create the plot with facets and labels
ggplot(mpg, aes(y = cty)) +
  geom_boxplot() +
  facet_grid(cols = vars(class)) +
  geom_text(data = mpg_summary, aes(x = Inf, y = Inf, label = label), hjust = 1, vjust = 1, size = 3) +
  theme(strip.text.x = element_blank())  # Remove facet labels

字符串
解释按“类别”分组并计算观测值、唯一模型和制造商。创建组合这些统计数据的标签字符串。
ggplot与geom_boxplot和facet_grid一起使用。
利用geom_text显示自定义标签。将标签放置在右上角,调整对齐和大小。通过使用主题(strip.text.x = element_blank())删除面标签来删除冗余标签。

相关问题