‘ggplot2’ package makes visualizing data easy!

‘geoms’ – the layers

  • Geoms are the layers that represent data points that you add to the plot space

  • Geom examples include: + points (geom_point', for scatter plots, dot plots, etc.) + lines (geom_line’, for time series, trend lines, etc.) + boxplot (`geom_boxplot’) + smooths (‘geom_smooth’, for adding regression lines, etc.)

  • You can add a geom to a plot using the ‘+’ operator

  • Note that the order in which you add layers matters! This is the order in which they will be displayed in the plot

aesthetics ‘aes’ control how layers/geoms look

  • aes examples include: + position (i.e., on the x and y axes) + color (“outside” color) + fill (“inside” color) + shape (of points) + linetype + size

  • Aesthetic mappings are set within geoms with the `aes()’ function

Other common visual elements – labels & theme

  • Axis and main figure labels can be added easily in ggplot: + Labs(x=“X axis”, y=“Y axis”, title=“Main Title”)

  • The ‘theme’ of the plot controls many of the plot characteristics, including: + Size of axis titles and labels (‘axis.title’ and ‘axis.text’) + Legend position (‘legend.position’) + Plot background (‘panel.background’)

Data visualization examples using ggplot2

load ggplot2 package

library(ggplot2) 

Linear models of species-specific harvest over time - example of stat_summary using geom=‘pointrange’

sig.sp = read.csv('linear_models_species_data_plot1.csv',stringsAsFactors = F)

ggplot(sig.sp, aes(x=year, y=log.harv.kg.ha, color=species))+
  stat_summary(fun.data = mean_cl_normal, geom = "pointrange")+
  geom_smooth(method='lm',se=F,aes(group=species))+
  scale_color_manual(breaks = c('BLACK CRAPPIE', 'BLUEGILL',"LARGEMOUTH BASS",'MUSKELLUNGE','WALLEYE'),
                     values=c('#a6cee3','#1f78b4','#b2df8a','#33a02c',"#cab2d6"))+
  scale_y_continuous(name=expression(log[e]*(Harvest+1)~(kg~ha^{-1})))+
  xlab("Year")+
  labs(color='Species')+
  theme_classic()+
  theme(legend.position = 'top')
## `geom_smooth()` using formula 'y ~ x'

Tiled heat map of species harvest - example of different ‘geom’, layered elements, and continuous color scale

tile = read.csv('tile_species_data_plot4.csv',stringsAsFactors = F)

ggplot(tile, aes(x=year,y=species,fill=as.factor(med.h.bin)))+
  geom_vline(xintercept = 1990, linetype='dotted')+
  geom_vline(xintercept = 1995, linetype='dotted')+
  geom_vline(xintercept = 2000, linetype='dotted')+
  geom_vline(xintercept = 2005, linetype='dotted')+
  geom_vline(xintercept = 2010, linetype='dotted')+
  geom_vline(xintercept = 2015, linetype='dotted')+
  geom_tile(size=0.1,na.rm=T,colour = "black")+
  scale_fill_viridis_d(direction=-1,
                       name = "Median\nHarvest"~(kg~ha^{-1}), 
                       labels = c('0.0-0.2','0.2-0.5','0.5-1.0','1.0-1.5','1.5-2.0','2.0-2.5','2.5-3.0'))+
  theme_classic()+
  xlab("Year")+ylab("")