Search code examples
rggplot2ridgeline-plot

Flipping Axes of ggplot


My dataframe looks like this:

df <- data.frame(label=c("yahoo","google","yahoo","yahoo","google","google","yahoo","yahoo"), year=c(2000,2001,2000,2001,2003,2003,2003,2003))

How is it possible to produce a thermal plot like this one:

library(ggplot2)
library(ggridges)
theme_set(theme_ridges())
ggplot(
  lincoln_weather, 
  aes(x = `Mean Temperature [F]`, y = `Month`)
  ) +
  geom_density_ridges_gradient(
    aes(fill = ..x..), scale = 3, size = 0.3
    ) +
  scale_fill_gradientn(
    colours = c("#0D0887FF", "#CC4678FF", "#F0F921FF"),
    name = "Temp. [F]"
    )+
  labs(title = 'Temperatures in Lincoln NE') 

How can I flip the plot axes, i.e. having year as the x axis and the label in y axis?


Solution

  • Well, simply use coord_flip(). See ggplot2 documentation. To make things neat, rotate the axis labels using axis.text.x and reorder the months LTR using scale_y_discrete:

    ggplot(
        lincoln_weather, 
        aes(x = `Mean Temperature [F]`, y = `Month`)
    ) +
        geom_density_ridges_gradient(
            aes(fill = ..x..), scale = 3, size = 0.3
        ) +
        scale_fill_gradientn(
            colours = c("#0D0887FF", "#CC4678FF", "#F0F921FF"),
            name = "Temp. [F]"
        )+
        labs(title = 'Temperatures in Lincoln NE') +
    coord_flip()+
    theme(axis.text.x = element_text(angle = 90, hjust=1))+
    scale_y_discrete(limits = rev(levels(lincoln_weather$Month)))
    

    Now this seems a bit weird, why scale_y and not scale_x? it appears that ggplot first constructs the plot elements and only then flips, rotates, applying styles and so on, and as the months are originally on the y axis, you need to use scale_y_discrete.

    If your data has now significant order, then you can obviously skip the whole scale_y_discrete thing.