knitr::opts_chunk$set(echo = TRUE, cache = TRUE)

Packages

Loading required packages:

scatter plot

data("iris")
ggplot(data=iris,aes(x=Sepal.Length, y=Sepal.Width,colour = Species))+geom_point(size=2, shape=15 )+facet_wrap(~Species)+labs(x="Sepal length",y="Sepal width", title = "Scatter plot")

Histogram

ggplot(data=iris)+ geom_histogram(aes(x=Sepal.Length,fill=Species),bins=10,col="white",alpha=0.7)+labs(x="Sepal length", title = "Histogram")

Reduce gap between Plot and Axis

ggplot(data = iris) + geom_histogram(
  
  aes(x = Sepal.Length, fill = Species),
  bins = 10,
  col = "white",
  alpha = 0.5
) + coord_cartesian(expand = FALSE)

ggplot(data = iris) + geom_histogram(
  
  aes(x = Sepal.Length, fill = Species),
  bins = 10,
  col = "white",
  alpha = 0.5
)+scale_y_continuous(
  breaks = seq(-10,30, by=5),
  expand = expansion(
    mult=c(0,0.5),   #expands upper portion of the plot by20%
    add = c(10,0)    # increases gap at the bottom portion by 10 unit
  )
)+scale_x_continuous(expand = expansion(add = c(0,0.8)))

Facet

facet_wrap and facet_grid

ggplot(data = iris) + geom_histogram(
  
  aes(x = Sepal.Length, fill = Species),
  bins = 10,
  col = "white",
  alpha = 0.5
)+ facet_wrap(vars(Species), ncol=1, scales="free")

iris %>% mutate(Species=factor(Species, levels = c("versicolor", "setosa", "virginica"))) %>% 


ggplot()+ geom_histogram(
  
  aes(x = Sepal.Length, fill = Species),
  bins = 10,
  col = "white",
  alpha = 0.5
)+ facet_grid(rows=vars(Species))

Theme

Built in theme

ggplot(data = iris) + geom_histogram(
  
  aes(x = Sepal.Length, fill = Species),
  bins = 10,
  col = "white",
  alpha = 0.5
)+facet_wrap(vars(Species), ncol=1)+ theme_minimal()

Other pre-built themes

ggplot(data = iris) + geom_histogram(
  
  aes(x = Sepal.Length, fill = Species),
  bins = 10,
  col = "white",
  alpha = 0.5
)+facet_wrap(vars(Species), ncol=1)+ theme_minimal()+
labs(
  title = "Histogram of Sepal length by species",
  x="Sepal length", 
  y="Frequency",
  fill="Species",
  subtitle = "Using facet and other customization",
  caption = "Data: iris"
  
)

Theme set globally

theme_set(theme_bw())

Manually changing colour

ggplot(data = iris) + geom_histogram(
  
  aes(x = Sepal.Length, fill = Species),
  bins = 10,
  col = "white",
  alpha = 0.5
)+facet_wrap(vars(Species), ncol=1)+ scale_fill_manual(values = c("setosa"="hotpink" ,"versicolor"="blue","virginica"="purple"))

#Palette

ggplot(data = iris) + geom_histogram(
  
  aes(x = Sepal.Length, fill = Species),
  bins = 10,
  col = "white",
  alpha = 1
)+facet_wrap(vars(Species), ncol=1)+ scale_fill_brewer(palette = "Set2")

#Contrast of colour(Hue)

ggplot(data = iris) + geom_histogram(
  
  aes(x = Sepal.Length, fill = Species),
  bins = 10,
  col = "white",
  alpha = 1
)+facet_wrap(vars(Species), ncol=1)+scale_fill_hue(
  l=80, c=150,   #adjust luminosity and chroma
  h=c(90,360)    # adjust range of hues
)