dbo
dbo

Reputation: 1234

ordering ggplot facets dynamically

What are recommended ways to order facets dynamically from left to right for:

(1) highest to lowest most recent price (so, b>a>c facets left to right) and

(2) highest to lowest average price (c>b>a)?

library(lubridate)
library(ggplot2)

start_date <- ymd("2019-04-01")
end_date <- ymd("2019-04-06")

date <- rep(seq(start_date, end_date, by = "days"),3)
price <- c(1,2,3,4,5,6,2,3,4,5,6,7,8,7,6,5,4,3)
class <- c(rep("a",6), rep("b",6), rep("c",6) )
df <- data.frame(date, price, class)

ggplot(df, aes(date, price)) + facet_wrap(~class) + geom_line()

enter image description here

Upvotes: 1

Views: 145

Answers (1)

shirewoman2
shirewoman2

Reputation: 1928

Are you asking how to get the facets to show up in that order? Make the faceting variable a factor and set the levels in the order you'd like. In your example:

 df$class <- factor(df$class, levels = c("b", "a", "c"))
 ggplot(df, aes(date, price)) + facet_wrap(~class) + geom_line()

Upvotes: 1

Related Questions