【问题标题】:How to add observation count (n) in ggplot2 scatter plot legend如何在ggplot2散点图图例中添加观察计数(n)
【发布时间】:2019-02-05 23:41:06
【问题描述】:

Image of legend i would like to add to

我想知道如何在 ggplot2 的散点图图例中添加一个简单的观察数 (n)

library(readr)
library(ggplot2)
library(dplyr)
All.mutations.no.inserts <- read_csv("All mutations no inserts.csv")
All.mutations.no.inserts$Fungicide <- factor(All.mutations.no.inserts$Fungicide, levels = c("SDHI 1",
                                                                   "SDHI 2",
                                                                   "SDHI 3",
                                                                   "SDHI 4",
                                                                   "SDHI 5",
                                                                   "SDHI 6",
                                                                   "SDHI 7",
                                                                   "SDHI 8",
                                                                   "SDHI 9",
                                                                   "SDHI 10",
                                                                   "SDHI 11",
                                                                   "SDHI 12"))
All.mutations.no.inserts$SDH.mutation <- factor(All.mutations.no.inserts$`SDH.mutation`)
ggplot(All.mutations.no.inserts, aes(x = Fungicide, y = EC50, color = SDH.mutation)) + 
  geom_point(size = 4) +
  scale_y_log10() +
  theme_minimal() +
  theme(axis.text.x=element_text(angle = -90, hjust = 0),
        axis.title.x=element_blank()) 

我应该如何修改我的代码?

【问题讨论】:

  • 欢迎来到 SO!请考虑创建一个最小的reproducible example
  • 谢谢,我是一个完整的菜鸟,我已经编辑了帖子并在其中插入了我的代码

标签: r ggplot2 legend


【解决方案1】:

这是一个使用 dplyr 的示例。查看代码中的 cmets。

library(dplyr)
library(ggplot2)

# sample data set
expand.grid(y = rnorm(20),
            x = letters[1:5],
            z = letters[6:10]) %>% 
  sample_frac(0.75) %>% 
  # add column n with counts for each group
  add_count(z) %>% 
  # combine the group z and count n into one column
  mutate(zn = paste0(z, ' (', n, ')')) %>% 
  # plot as you had
  ggplot(aes(x, y, colour = zn)) +
  geom_point() +
  # rename the legend title
  labs(colour = 'z (# obs)')

reprex package (v0.2.1) 于 2019 年 2 月 6 日创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多