Creating multiple plots using same dataframe using conditions in ggplot2

I have a dataframe of airports with year and respective cost. I want to create a single plot showing how the price is increasing over the years for all the 4 airports.

#I can plot for individual airport like below
ggplot((df %>% filter(Airport == 'ORD')), aes(x=year, y=cost)) + geom_line(color = "blue") + geom_point()

#But I am unable to find a reasonable way to have all 4 airports to be displayed in same graph. 
#I tried reshape and melt but the data did not make sense to me.

Dataframe example

Airport Year Cost
ORD 2011 100
SFO 2011 150
SJC 2011 200
EWR 2011 250
ORD 2012 150
SFO 2012 200
SJC 2012 250
EWR 2012 300
ORD 2013 200
SFO 2013 250
SJC 2013 300
EWR 2013 350

One of these?

library(ggplot2)

df <- data.frame(
  stringsAsFactors = FALSE,
           Airport = c("ORD","SFO","SJC","EWR",
                       "ORD","SFO","SJC","EWR","ORD","SFO","SJC","EWR"),
              Year = c(2011L,2011L,2011L,2011L,
                       2012L,2012L,2012L,2012L,2013L,2013L,2013L,2013L),
              Cost = c(100L,150L,200L,250L,150L,
                       200L,250L,300L,200L,250L,300L,350L)
)

ggplot(df, aes(Year, Cost, col = Airport)) +
  geom_line()

ggplot(df, aes(Year, Cost)) +
  geom_line() +
  facet_wrap(~Airport)

Yes this is perfect. I was trying something else. Never figured the solution is so simple. Thanks!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.