Ski bum
Ski bum

Reputation: 41

R Coding for ggridges

I am new to coding in R so please excuse the simple question. I am trying to run ggridges geom in R to create monthly density plots. The code is below, but it creates a plot with the months in the wrong order:enter image description here

The code references a csv data file with 3 columns (see image) - MST, Aeco_5a, and month:enter image description here Any suggestions on how to fix this would be greatly appreciated. Here is my code:

> library(ggridges)
> read_csv("C:/Users/Calvin Johnson/Desktop/Aeco_Price_2017.csv")
Parsed with column specification:
cols(
  MST = col_character(),
  Month = col_character(),
  Aeco_5a = col_double()
)
# A tibble: 365 x 3
         MST   Month Aeco_5a
       <chr>   <chr>   <dbl>
 1  1/1/2017 January  3.2678
 2  1/2/2017 January  3.2678
 3  1/3/2017 January  3.0570
 4  1/4/2017 January  2.7811
 5  1/5/2017 January  2.6354
 6  1/6/2017 January  2.7483
 7  1/7/2017 January  2.7483
 8  1/8/2017 January  2.7483
 9  1/9/2017 January  2.5905
10 1/10/2017 January  2.6902
# ... with 355 more rows
> 
> mins<-min(Aeco_Price_2017$Aeco_5a)
> maxs<-max(Aeco_Price_2017$Aeco_5a)
> 
> ggplot(Aeco_Price_2017,aes(x = Aeco_5a,y=Month,height=..density..))+
+     geom_density_ridges(scale=3) +
+     scale_x_continuous(limits = c(mins,maxs)) 

Upvotes: 0

Views: 1112

Answers (1)

twedl
twedl

Reputation: 1648

This has two parts: (1) you want your months to be factor instead of chr, and (2) you need to order the factors the way we typically order months.

With some reproducible data:

library(ggridges)
df <- sapply(month.abb, function(x) { rnorm(10, rnorm(1), sd = 1)}) 
df <- as_tibble(x) %>% gather(key = "month")

Then you need to mutate month to be a factor, and use the levels defined by the actual order they show up in the data.frame (unique gives the unique levels in the dataset, and orders them in the way they're ordered in your data ("Jan", "Feb", ...)). Then you need to reverse them, because this way "Jan" will be at the bottom (it's the first factor).

df %>% 
  # switch to factor, and define the levels they way you want them to show up 
  # in the ggplot; "Dec", "Nov", "Oct", ... 
  mutate(month = factor(month, levels = rev(unique(df$month)))) %>% 
  ggplot(aes(x = value, y = month)) + 
  geom_density_ridges()

Upvotes: 1

Related Questions