How to subset in ggplot based on two character variables?

Viewed 111

I am trying to subset my data in ggplot based on two characters variables: model and letter. I want to subset "m1" who has the letter "a". In the original data, i have multiple rows who has "m1" and "a", but below is just a small reproducible example. Can someone guide me with how to subset it inside the command of ggplot?

model   value   letter
m1        5       a
m2        11      b
m3        2       c
m1        4       d
m2        22      e
m3        6       f

 structure(list(model = structure(c("m1", "m2", "m3", "m1", "m2", 
"m3"), format.stata = "%9s"), value = structure(c(5, 11, 2, 4, 
22, 6), format.stata = "%9.0g"), letter = structure(c("a", "b", 
"c", "d", "e", "f"), format.stata = "%9s")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))
2 Answers

We could do a group by filter and this can be used as input to ggplot

library(dplyr)
library(ggplot2)
df1 %>% 
    group_by(model) %>%
    filter('a' %in% letter)  %>%
    ggplot(aes(x = letter, y = value)) +
       geom_col()

Or if it is just 'm1' and 'a', do the filter at once

df1 %>%
    filter(model == 'm1', letter == 'a') %>%
     ggplot(aes(x = letter, y = value)) +
       geom_col()

Does this work?

ggplot(subset(df,model=='m1' & letter=='a'),aes(x=letter,y=value))+
  geom_point()

Explanation:

In ggplot2 the data argument allows using other functions like subset().

Related