I am interested in displaying only the top 3 most abundant groups in my ggplot2 legend.
for example, in this table, i have 7 groups and i would only like to display groups D, E, F in my ggplot2 legend
group | sample size |
---|---|
A | 2 |
B | 3 |
C | 1 |
D | 25 |
E | 23 |
F | 20 |
G | 3 |
I tried searching online but the closest answers i got was to reorder the legend.
Thanks in advance!
Cheers, Mel
You could achieve this by setting the breaks
for the fill scale:
df <- data.frame(
group = c("A", "B", "C", "D", "E", "F", "G"),
sample.size = c(2L, 3L, 1L, 25L, 23L, 20L, 3L)
)
library(ggplot2)
library(dplyr)
top_group <- df %>% top_n(3, sample.size) %>% pull(group)
ggplot(df, aes(group, sample.size, fill = group)) +
geom_col() +
scale_fill_discrete(breaks = top_group)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.