#### Pretty ggplots examples 

library(dslabs)
head(murders)


## ----ggplot-example-plot-0, echo=FALSE, message=FALSE, warning=FALSE----------------------
library(tidyverse)
library(ggthemes)
library(ggrepel)

############# Example 1 
r <- murders |> 
  summarize(pop = sum(population), tot = sum(total)) |> 
  mutate(rate = tot/pop*10^6) |> pull(rate)

murders |> ggplot(aes(x = population/10^6, y = total, label = abb)) +  
  geom_abline(intercept = log10(r), lty = 2, col = "darkgrey") +
  geom_point(aes(color = region), size = 3) +
  geom_text_repel() + 
  scale_x_log10() +
  scale_y_log10() +
  xlab("Populations in millions (log scale)") + 
  ylab("Total number of murders (log scale)") +
  ggtitle("US Gun Murders in 2010") +
  scale_color_discrete(name = "Region") +
  theme_economist()

##### Example 2: heatmap 
the_disease <- "Measles"
dat <- us_contagious_diseases |>
  filter(!state%in%c("Hawaii","Alaska") & disease == the_disease) |>
  mutate(rate = count / population * 10000 * 52 / weeks_reporting) |>
  mutate(state = reorder(state, rate))

jet.colors <-
colorRampPalette(c("#F0FFFF", "cyan", "#007FFF", "yellow", "#FFBF00", "orange", "red", "#7F0000"), bias = 2.25)

dat |> ggplot(aes(year, state, fill = rate)) +
  geom_tile(color = "white", linewidth = 0.35) +
  scale_x_continuous(expand = c(0,0)) +
  scale_fill_gradientn(colors = jet.colors(16), na.value = 'white') +
  geom_vline(xintercept = 1963, col = "black") +
  theme_minimal() + 
  theme(panel.grid = element_blank()) +
  coord_cartesian(clip = 'off') +
  ggtitle(the_disease) +
  ylab("") +
  xlab("") +  
  theme(legend.position = "bottom", text = element_text(size = 8)) + 
  annotate(geom = "text", x = 1963, y = 50.5, label = "Vaccine introduced", size = 3, hjust = 0)
######### Example 3: Barchat 

nyc_regents_scores$total <- rowSums(nyc_regents_scores[,-1], na.rm = TRUE)

nyc_regents_scores |> 
  filter(!is.na(score)) |>
  ggplot(aes(score, total)) + 
  annotate("rect", xmin = 65, xmax = 99, ymin = 0, ymax = 35000, alpha = .5) +
  geom_bar(stat = "identity", color = "black", fill = "#C4843C") + 
  annotate("text", x = 66, y = 28000, label = "MINIMUM\nREGENTS DIPLOMA\nSCORE IS 65", hjust = 0, size = 3) +
  annotate("text", x = 0, y = 12000, label = "2010 Regents scores on\nthe five most common tests", hjust = 0, size = 3) +
  scale_x_continuous(breaks = seq(5, 95, 5), limits = c(0,99)) + 
  scale_y_continuous(position = "right", labels = scales::comma) +
  ggtitle("Scraping by") + 
  xlab("") + ylab("Number of tests") + 
  theme_minimal() + 
  theme(panel.grid.major.x = element_blank(), 
        panel.grid.minor.x = element_blank(),
        axis.ticks.length = unit(-0.2, "cm"),
        plot.title = element_text(face = "bold"))
        
#################################
### ggplot from scratch 
#################################
## 
## Data |> ggplot() + LAYER 1 + LAYER2 + ... + LAYER N

## ----message=FALSE, warning=FALSE---------------------------------------------------------
#| cache: false
library(dplyr)
library(ggplot2)


## ----ggplot-example-plot, echo=FALSE------------------------------------------------------
library(dslabs)
library(ggthemes)
library(ggrepel)

r <- murders |> 
  summarize(pop = sum(population), tot = sum(total)) |> 
  mutate(rate = tot/pop*10^6) |> pull(rate)

murders |> ggplot(aes(x = population/10^6, y = total, label = abb)) +  
  geom_abline(intercept = log10(r), lty = 2, col = "darkgrey") +
  geom_point(aes(color = region), size = 3) +
  geom_text_repel() + 
  scale_x_log10() +
  scale_y_log10() +
  xlab("Populations in millions (log scale)") + 
  ylab("Total number of murders (log scale)") +
  ggtitle("US Gun Murders in 2010") +
  scale_color_discrete(name = "Region") +
  theme_economist()


## ----echo=FALSE---------------------------------------------------------------------------
theme_set(theme_grey()) ## to imitate what happens with setting theme


## -----------------------------------------------------------------------------------------
#| cache: false
library(dslabs)


## -----------------------------------------------------------------------------------------
#| eval: false
## ggplot(data = murders)


## ----ggplot-example-1---------------------------------------------------------------------
murders |> ggplot()


## -----------------------------------------------------------------------------------------
p <- ggplot(data = murders)


## -----------------------------------------------------------------------------------------
#| eval: false
## print(p)
## p


## ----ggplot-example-2---------------------------------------------------------------------
murders |> ggplot() + geom_point(aes(population/10^6, total))


## ----ggplot-example-3---------------------------------------------------------------------
murders |> ggplot() + 
  geom_point(aes(population/10^6, total)) +
  geom_text(aes(population/10^6, total, label = abb))


## -----------------------------------------------------------------------------------------
#| eval: false
 murders |> ggplot(aes(population/10^6, total)) +
   geom_point() +
   geom_text(aes(label = abb))


## ----ggplot-example-4---------------------------------------------------------------------
murders |> ggplot(aes(population/10^6, total)) +
  geom_point() +
  geom_text(aes(x = 10, y = 800, label = "Hello there!"))


## ----ggplot-example-5---------------------------------------------------------------------
murders |> ggplot(aes(population/10^6, total)) +
  geom_point(size = 3) +
  geom_text(aes(label = abb), nudge_x = 1.5)


## ----ggplot-example-6---------------------------------------------------------------------
murders |> ggplot(aes(population/10^6, total)) +
  geom_point(aes(color = region), size = 3) 


## ----ggplot-example-7---------------------------------------------------------------------
murders |> ggplot(aes(population/10^6, total)) +
  geom_point(color = "blue", size = 3) 


## -----------------------------------------------------------------------------------------
p0 <- murders |> ggplot(aes(population/10^6, total))


## -----------------------------------------------------------------------------------------
p1 <- p0 +  geom_point(aes(color = region), size = 3)


## -----------------------------------------------------------------------------------------
p2 <- p1 + geom_text(aes(label = abb), nudge_x = 0.3)


## ----ggplot-example-8---------------------------------------------------------------------
p3 <- p2 + scale_x_log10() + scale_y_log10() 
p3


## ----ggplot-example-9---------------------------------------------------------------------
p4 <- p3 + labs(title = "US Gun Murders in 2010",
                x = "Populations in millions (log scale)", 
                y = "Total number of murders (log scale)",
                color = "Region")
p4



## -----------------------------------------------------------------------------------------
r <- murders |> 
  summarize(rate = sum(total)/sum(population)*10^6) |> 
  pull(rate)


## ----ggplot-example-10--------------------------------------------------------------------
p5 <- p4 + 
  geom_abline(intercept = log10(r), lty = 2, color = "darkgrey") 
p5


## -----------------------------------------------------------------------------------------
ds_theme_set()


## -----------------------------------------------------------------------------------------
library(ggthemes)
p6 <- p5 + theme_economist()

p7<-p5+ theme_fivethirtyeight()

## ----final-ggplot-example-----------------------------------------------------------------
library(ggthemes)
library(ggrepel)

r <- murders |> 
  summarize(rate = sum(total) /  sum(population) * 10^6) |>
  pull(rate)

murders |> 
  ggplot(aes(population/10^6, total)) +   
  geom_abline(intercept = log10(r), lty = 2, color = "darkgrey") +
  geom_point(aes(col = region), size = 3) +
  geom_text_repel(aes(label = abb)) + 
  scale_x_log10() +
  scale_y_log10() +
  labs(title = "US Gun Murders in 2010",
                x = "Populations in millions (log scale)", 
                y = "Total number of murders (log scale)",
                color = "Region") +
  theme_economist()


## ----echo=FALSE---------------------------------------------------------------------------
ds_theme_set()


## ----barplot-geom-------------------------------------------------------------------------
#| eval: false
 murders |> ggplot(aes(region)) + geom_bar()


## -----------------------------------------------------------------------------------------
tab <- murders |> 
  count(region) |> 
  mutate(proportion = n/sum(n))


## ----region-freq-barplot------------------------------------------------------------------
#| eval: false
tab |> ggplot(aes(region, proportion)) + geom_col()


## ----eval=FALSE---------------------------------------------------------------------------
 heights |> filter(sex == "Female") |>
   ggplot(aes(height)) +
      geom_histogram(binwidth = 1, fill = "blue", col = "black")


## ----eval=FALSE---------------------------------------------------------------------------
 heights |>
   filter(sex == "Female") |>
   ggplot(aes(height)) +
   geom_density(fill = "blue")


## ----eval = FALSE-------------------------------------------------------------------------
 heights |>
   filter(sex == "Female") |>
   ggplot(aes(height)) +
   geom_density(fill="blue", adjust = 2)


## ----female-male-boxplots-geom, eval=FALSE------------------------------------------------
 heights |> ggplot(aes(sex, height)) +
   geom_boxplot()


## -----------------------------------------------------------------------------------------
x <- expand.grid(x = 1:12, y = 1:10) |> mutate(z = 1:120) 


## ----eval=FALSE---------------------------------------------------------------------------
 x |> ggplot(aes(x, y, fill = z)) + geom_raster()


## ----ggplot2-image-new-colors-------------------------------------------------------------
x |> ggplot(aes(x, y, fill = z)) + 
  geom_raster() + 
  scale_fill_gradientn(colors =  terrain.colors(10, 1))


## ----gridExtra-example, warning=FALSE, message=FALSE, fig.height=4, fig.width=12, out.width="100%"----
library(gridExtra)
grid.arrange(p5, p6, ncol = 2)



