GGplot2 cheatsheet

1 minute read

In this blog post I will include some useful tips for visualize data with ggplot2

Commands

Add translucid background

theme() +
  theme(panel.border = element_blank(),
        legend.key = element_blank(),
        axis.ticks = element_blank(),
        axis.text.y = element_blank(),
        axis.text.x = element_blank(),
        panel.grid = element_blank(),
        panel.grid.minor = element_blank(), 
        panel.grid.major = element_blank(),
        panel.background = element_blank(),
        plot.background = element_rect(fill = "transparent",colour = NA))

ggsave("C:/path/to/save/file.png", bg = "transparent", width = 50, height = 50, units = "cm")  

plot several graphs according to a variable

facet_wrap(~variable)+ 

Useful combos

Combo1

turn wide dataframes into long dataframes

library(reshape2)


long_dataframe <- melt(wide.data.frame[,c("columns","you","care")],  #in case your dataframes has several columns and you only need 3 or 4
                     variable.name = "category", 
                     value.name = "value",id.vars = c("sample_id") 
) #- Read more at: http://scq.io/KBYDSxie#gs.6XHfLQU

subset the long dataframe

long_dataframe<- subset(long_dataframe, sample_id %in% c(value:higher_value))

plot by category

p <- ggplot() +
  geom_point(aes(x = sample_id, y = value, colour = category), data = long_dataframe, shape = 20, size = 1) +
  scale_color_manual(values = c("category1" = "dark blue","category2" = "violetred3" ), name = "my categories",labels = c("category 1" = "cool name for category", "category 2" = "another cool name")) +
  scale_y_continuous(limits = c(0, 2000), expand = c(0, 0))+
  scale_x_continuous(expand = c(0, 0))+
  labs(x = "sample_id", y = "value") +
  ggtitle(" fake figure") +
  theme() +
  theme_bw() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        plot.title = element_text(size = rel(1.2), face = "bold", vjust = 1.5))


ggsave("C:/path/where/you/will/save/the/figure/fig.png", width = 50, height = 30, units = "cm")  

override the default size of the legend to increase its size

guides(colour = guide_legend(override.aes = list(size=5))) 

theme

change default theme

theme_set(theme_grey())

control the theme

minor breaks control the horizontal lines. seq function allow to put lines in a sequence of numbers

scale_y_continuous(limits = c(0, 8), minor_breaks = seq(0 , 8, 1), breaks = seq(0 , 8, 2), expand = c(0, 0))+

minor.grid.minor controls the colour and size of the theme lines

  theme(
        panel.grid.minor = element_line(colour="white", size=0.5),
        legend.title = element_text(size = 12, face = "bold"), #control legend title
        plot.title = element_text(size = 16, face = "bold", hjust = 0.5), #control 
        axis.text  = element_text(size=16),   #control size of axis text   
        axis.title = element_text(size = 16, face = "bold")) # control title text

Leave a Comment