如何在ggplot2散点图图例中添加观察计数(n)

时间:2019-02-05 23:41:06

标签: r ggplot2 legend

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()) 

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

1 个答案:

答案 0 :(得分:1)

这是使用dplyr的示例。请参阅代码中的注释。

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-02-06创建