Packages

Loading required packages :

library(ggplot2)
library(dplyr)
library(readxl)
library(ggthemes)
library(ggThemeAssist)
library(forcats)
library(ggpubr)
library(patchwork)

header 1

This plot is shows the relationship between X and Y

Scattar Plot

ggplot(data = iris)+
  aes(x= Sepal.Length, y = Sepal.Width) + geom_point(col="tan",size= 3,shape=22)+
  facet_wrap(~Species) +
  labs(title = "Scatter plot of Sepal.Length and Sepal.Width ",x = "Sepal Length" , y = "Sepal Width" )

ggplot(data = iris,aes(x = Sepal.Length, y = Sepal.Width,colour = Species)) + 
  geom_point()+
  labs(title = "Scatter plot of Sepal.Length and Sepal.Width ",x = "Sepal Length" ,y = "Sepal Width",  col = "Speacies Legend" )

Histogram

ggplot(data = iris) +
  geom_histogram(aes(x = Sepal.Length),binwidth = 0.5,fill = "lightblue",col = "black")

ggplot(data = iris) +
  geom_histogram(aes(x = Sepal.Length),bins = 10,fill = "lightblue",col  = "black")

ggplot(data = iris) +
  geom_histogram(aes(x = Sepal.Length,fill = Species),bins = 10,col  = "black",alpha =1) +
  scale_y_continuous(
    breaks = seq(-10,30,by= 5),
    expand = expansion(
      mult = c(0,0.2),# expand upper portion of the plot by 20 %
      add = c(10,0) #increase gap of the bottom by 10 unit
    )
  )+
  scale_x_continuous(expand = expansion(add = c(1,1))) #first is lower limit and second is upper limit

#tinytex::install_tinytex()
#install.packages("officer")
#install.packages("ggthemes")
#install.packages("ggThemeAssist")
#tinytex::install_tinytex(force = TRUE)
#Reduce gap between Plot and axis

#tinytex::tinytex_root()
#tinytex::pdflatex("test.tex")  # optional test

Facet———————————

facet_wrap

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

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

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

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

facet_grid

ggplot(data = iris) +
  geom_histogram(aes(x = Sepal.Length,fill = Species),bins = 10,col  = "black",alpha =1) +
  facet_grid(rows = vars(Species))

student <- readxl::read_excel("Data/StudentSurveyData.xlsx")

ggplot(data = student) +
  geom_histogram(aes(x = GPA,fill = Employment),bins = 10,col  = "black",alpha =1) +
  facet_grid(rows = vars(Employment),cols= vars(Gender))

ggplot(data = student) +
  geom_histogram(aes(x = GPA,fill = Employment),bins = 10,col  = "black",alpha =1) +
  facet_grid(rows = vars(Employment),cols= vars(Class))

student %>% 
  mutate(Class = factor(Class,levels = c("Freshman","Sophomore","Junior","Senior"))) %>% 
  ggplot() +
  geom_histogram(aes(x = GPA,fill = Employment),bins = 10,col  = "black",alpha =1) +
  facet_grid(rows = vars(Employment),cols= vars(Class))

Theme——————————–

Built in ggplot theme

##Built in ggplot theme
ggplot(data = iris) +
  geom_histogram(aes(x = Sepal.Length,fill = Species),bins = 10,col  = "black",alpha =1) +
  facet_wrap(vars(Species),ncol = 1)+
  theme_bw()

## Themes from other packages

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

Set theme globally

theme_set(theme_solarized())

Manually changing color

ggplot(data = iris) +
  geom_histogram(aes(x = Sepal.Length,fill = Species),bins = 10,col  = "black",alpha =1) +
  facet_wrap(vars(Species),ncol = 1)+
  scale_fill_manual(values = c("setosa" = "#6C1C80","versicolor" = "#30A19c","virginica" = "#123896"))

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

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

Density Plot

ggplot(data = iris,aes(x = Sepal.Length,fill = Species)) +
  geom_density(alpha = 0.7, color = "black")+
  geom_histogram(aes(y = after_stat(density)),alpha = 0.6,bins = 10)+
  facet_wrap(vars(Species),ncol = 1)

ggplot(iris, aes(Sepal.Length))+
  geom_histogram(aes(y = after_stat(density)),
                 color = "#000000",fill = "#0099F8")+
  geom_density(color = "#000000",fill = "#0EE100",alpha = 0.5)+
  geom_vline(aes(xintercept = mean(Sepal.Length)),
             color = "#000000",size = 1,linetype = "dashed")+
  labs(
    title = "Distribution of Sepal Length ",
    subtitle = "Made by ggplot2",
    caption = "Source:iris Data",
    x = "Sepal Length",
    y = "Density"
    
  )+
  theme(
    plot.title = element_text(color = "blue",size = 16,face = "bold"),
    plot.subtitle = element_text(color = "violet" ,size = 16),
    plot.caption = element_text(face = "italic")
  )+
  annotate("text",x = 6,y = 0.45,
           label = paste0("Mode: ",+
  round(DescTools::Mode(iris$Sepal.Length),1) ), hjust = 0 )
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

geom_bar

ggplot(student)+
  geom_bar(aes(x= Computer))

ggplot(student)+
  geom_bar(aes(x= Computer))+
  coord_flip()

ggplot(student)+
  geom_bar(aes(y= Computer))

geom_col

student %>% 
  count(Computer) %>% 
  ggplot()+
  geom_col(aes(x = Computer,y = n))

student %>% 
  count(Computer) %>% 
  ggplot()+
  geom_col(aes(x = Computer,y = n))+
  labs(y = "Number of students")+
  coord_flip()

student %>% 
  count(Computer) %>% 
  ggplot()+
  geom_bar(aes(x = Computer,y = n),stat = "identity")+
  labs(y = "Number of students")+
  coord_flip()

Arrenging bars

geom_bar modification

ggplot(student)+
  geom_bar(aes(x = Computer))+
  scale_x_discrete(limits = c("Laptop","Desktop","Tablet"))

library(forcats)


ggplot(student)+
  geom_bar(aes(x = fct_infreq(Computer)))

ggplot(student)+
  geom_bar(aes(x = fct_infreq(Computer) %>% fct_rev()))

ggplot(student)+
  geom_bar(aes(x = fct_infreq(Computer)),fill= c("black","bisque3","red3"))+
  labs(
    x = "Computer usage",y = "Frequency",
    title = "A simple bar plot"
  )

ggplot(student)+
  geom_bar(aes(x = Computer,fill= Computer ))+
             scale_fill_manual(values = c("black","bisque3","red3"))

geom_col modification

student %>% 
  count(Computer) %>% 
  ggplot()+
  geom_bar(aes(x = Computer,y = n),stat = "identity")+
  labs(y = "Number of students")+
   scale_x_discrete(limits = c("Laptop","Desktop","Tablet"))

student %>% 
  count(Computer) %>% 
  ggplot(aes(x =reorder(Computer, -n),y = n,label = n))+
  geom_col()+
  geom_text(vjust = -1.6,color = "blue",size = 3.5)+
  labs(y = "Number of students")+
    ylim(0,100)

 student %>% 
  count(Computer,Class) %>% 
  ggplot(aes(x =reorder(Computer, -n),y = n))+
  geom_col()+
  geom_text(aes(label= n) , vjust = -1.6,color = "blue",size = 3.5)+
  labs(y = "Number of students")+
   theme_minimal()+
   facet_wrap(vars(Class))+
   ylim(0,35)

 student %>% 
  count(Computer,Class) %>% 
  ggplot(aes(x =reorder(Computer, -n),y = n))+
  geom_col(fill = "royalblue")+
  geom_text(aes(label= n) , vjust = -1.6,color = "blue",size = 3.5)+
  labs(y = "Number of students")+
   theme_light()+
   facet_wrap(vars(Class))+
   ylim(0,35)+
   labs(
     x = "Device usages",y = "Freq", title = "Frequency of device use by class"
   )+
   theme(plot.title = element_text(hjust = 0.5),
         strip.text = element_text(colour = "#0EE990"))

ggplot(student,aes(y = Major))+
  geom_bar()+
  geom_text(aes(x = after_stat(count  + 1),label = after_stat(count)),
            stat = "count",
            size = 3 )+
  labs(
    x = "Freq" , y = NULL
  )

Stacked and Percentage Filled Bar Plot

ggplot(student)+
  geom_bar(aes(x = Class , fill = Employment))

ggplot(student)+
  geom_bar(aes(x = Class , fill = Employment),position = "stack")

ggplot(student)+
  geom_bar(aes(x = Class , fill = Employment),position = "dodge")

ggplot(student)+
  geom_bar(aes(x = Class , fill = Employment),position = "fill")

Aranging bars

student %>% 
  mutate(Class = factor(Class , levels = c("Freshman","Sophomore","Junior","Senior"))) %>% 
  ggplot()+
  geom_bar(aes(x = Class, fill = Employment),position = "fill")

ggplot(student, aes(x = Class, fill = Employment)) +
  geom_bar(position = "fill") +
  geom_text(aes(label = after_stat(count)),size = 3,
            stat = "count",position =  position_fill(vjust = 0.5))

CGPfunctions :: PlotXTabs2(
  data = student,
  y = Gender ,
  x = Computer,
  results.subtitle = FALSE,
  sample.size.label = TRUE,palette = "Set2",
  ggtheme = ggplot2 :: theme_bw()
  
)

#install.packages("CGPfunctions")

Legend customization

Legend possition

ggplot(data = iris) +
  geom_point(aes(x = Sepal.Length , y = Sepal.Width,col = Species,size = Petal.Length))+
  
  labs(x = "Sepal Length",y = "Sepal width",title = "Scatter plot of Sepal Length and width ") +
  theme(legend.position = "bottom")

Axis customization

#install.packages("scales")

ggplot(student, aes(x = Class, fill = Employment)) +
  geom_bar(position = "fill") +
  geom_text(aes(label = after_stat(count)),size = 3,
            stat = "count",position =  position_fill(vjust = 0.5))+
  scale_y_continuous(labels = scales::percent_format(accuracy = 0.1))

Box Plot

ggplot(student,aes(x = Class,y = Spending)) +
  geom_boxplot() +
  geom_jitter()

iris %>% 
  ggplot(aes(x = Species, y = Sepal.Length))+
  geom_boxplot() +
  geom_jitter()

#install.packages("ggpubr")

Code for ggpubs

student %>% 
  mutate(Class = factor(Class, levels =c ("Freshman","Sophomore","Junior","Senior") )) %>% 
  ggboxplot(x = "Class", y = "Spending",
            color = "Class", palette = c("#00AFBB","#E7BB00","#FCAE07","black"),
add = "jitter",shape = "Class")+
  theme(legend.position = "none") +
  geom_pwc(method = "t_test")+
  stat_compare_means(method = "anova",label.y = 50)

library(ggpubr)
library(dplyr)

student %>% 
  mutate(Class = factor(Class, levels = c("Freshman","Sophomore","Junior","Senior"))) %>% 
  ggboxplot(
    x = "Class",
    y = "Spending",
    color = "Class",
    palette = c("#00AFBB","#E7BB00","#FCAE07","black"),
    add = "jitter",
    shape = "Class"
  ) +
  theme(legend.position = "none") +
  geom_pwc(method = "t_test") +
  stat_compare_means(method = "anova", label.y = 50)

 #install.packages("esquisse") 

ggplot(student) +
  aes(x = Class, fill = `Grad Intention`) +
  geom_bar() +
  scale_fill_hue(direction = 1) +
  ggthemes::theme_wsj()

Combining multiple plot

patchwork

#install.packages("patchwork")

library(patchwork)

ggarrange

#install.packages("gridExtra")

plotly

p4 <- iris %>% 
  ggplot(aes(x = Species,y = Sepal.Length))+
  geom_boxplot()+
  geom_jitter()
plotly::ggplotly()