---
title: "Warwick R User Group: dRugs"
author: "Kenneth T K Lim"
date: "13 March 2019"
output: 
  html_document:
    code_folding: hide
---
## Purpose
Data visualisation of drug harm for WRUG^[https://www.meetup.com/Warwick-useRs/events/259364376/], based on a monthly reddit challenge^[https://www.reddit.com/r/dataisbeautiful/comments/an18kt/battle_dataviz_battle_for_the_month_of_february/].

## Original data

+ Get data directly from website.

```{r setup, warning=FALSE, message=FALSE}
#Load the following libraries (install if you don't have them)
library(rvest) #Scrape web pages
library(dplyr) #Data manipulation
library(ggplot2) #Data visualisation
library(emo) #emoji package for getting symbols, install from here: https://github.com/hadley/emo
library(emojifont) #emoji package for plotting, install from here: https://github.com/GuangchuangYu/emojifont
library(knitr) #Display nicer looking tables in html file
library(tidyr) #Reshape data (wide to long)
library(gridExtra) #Put plots side by side in html file

#Read data from webpage and extract the data table
url <- "https://commons.wikimedia.org/wiki/File:Development_of_a_rational_scale_to_assess_the_harm_of_drugs_of_potential_misuse_(physical_harm_and_dependence,_NA_free_means).svg#Data"
pg <- read_html(url)
tab <- html_table(pg, fill = TRUE, header = TRUE)[[5]] #table stored in the 5th element of the list (visual inspection)
```

+ The data set has `r nrow(tab)` rows and `r ncol(tab)` columns. These are the first 6 rows and 6 columns as an example:

```{r tab1}
knitr::kable(head(tab[1:6, 1:6])) #for illustration only
```

## From the drawing board...to R?

One day, I asked Lewis Rendell for some ideas on displaying the data. To illustrate his very complex idea, he drew it out on a whiteboard:

<p style="text-align:center;">
![Lewis' drawing in the Warwick Statistics office room](https://warwick.ac.uk/fac/sci/statistics/staff/research_students/lim/img_5542.jpg){width=600px}
</p>

I liked his idea so much that I decided to make a plot that resembles his drawing (and learn about using emojis in R)!

## Data cleaning

+ Select and rename relevant columns (`dplyr` package), reshape data set from wide to long (`tidyr`) and get emojis (`emo`). _Note: emoji packages were downloaded from Github and not CRAN_^[`emojifont`: https://guangchuangyu.github.io/2015/12/use-emoji-font-in-r/] ^[`emo`: https://github.com/hadley/emo]

```{r}
#Select the relevant columns/variables
#Rename the variables
#Reshape data from wide to long (tidyr::gather)
tab <- tab %>%
  select("Drug", "MeanNA=0 Physical harm[3]", "Mean Dependence", "Mean Social harm") %>%
  rename(mean_physical = "MeanNA=0 Physical harm[3]",
         mean_dependence = "Mean Dependence",
         mean_social = "Mean Social harm") %>% 
  tidyr::gather("category", "score", mean_physical:mean_social)

#Create a new column called emo, 
##which takes different emojis depending on the category
tab$emo[tab$category=="mean_physical"] <- emo::ji("punch")
tab$emo[tab$category=="mean_dependence"] <- emo::ji("fishing_pole_and_fish")
tab$emo[tab$category=="mean_social"] <- emo::ji("broken")
#Had to replace punch emoji for the nauseated face emoji on the whiteboard
```

+ Example of dataframe

```{r }
#Selected rows for illustration purposes
knitr::kable(tab[c(1:2, 24:25, 59:60),], align = c("l", "l", "r", "c"))
```

+ Physical harm: `r emo::ji("punch")` (punch)

+ Dependence: `r emo::ji("fishing_pole_and_fish")` (hooked...)

+ Social harm: `r emo::ji("broken")` (heart break for others)

## Data visualisation

Mean scores for dependence, physical harm and social harm for each drug, ordered by decreasing mean dependence score (blue fish hook).

+ Emojis represented as text (`emojifont`), so they have slightly different appearance.
    
    + Difficult to represent otherwise, as the rendering depends on operating system. For same reason, it is difficult to use emojis as legend symbols.

```{r, fig.showtext=TRUE, out.width = '90%', fig.align='center', warning = FALSE, message = FALSE}
id_order <- tab %>%
  ungroup() %>%
  arrange(category, score) %>% #arrange category and then scores within
  distinct(Drug) %>% #get unique value of drug
  unlist()
#id_order: order of Drugs that will be used for subsequent plot

#emojifont::list.emojifonts()
emojifont::load.emojifont('OpenSansEmoji.ttf') #load this for graphical display

#Plot with emoji
tab %>%
  ggplot(aes(x = factor(Drug, levels = id_order), y = score, col = category)) +
  geom_point(size = 0, alpha = 0) + #hide points as work around; only for legend purposes
  geom_text(aes(label = emo), family="OpenSansEmoji", size = 4.75, show.legend = FALSE) +
  #emoji as text, and hide legends (use legends from geom_point())
  scale_y_continuous(breaks = seq(from = 0.5, to = 3, by = 0.5)) +
  scale_colour_manual(labels = c("Dependence (hook)", "Physical harm (punch)", "Social harm (heart)"), values = c("blue", "black", "red")) + #change labels and colours manually
  coord_flip() + #flip coordinates for horizontal x axis
  theme_bw() +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major.x = element_blank(), #just keep the horizontal grid lines
        axis.title = element_text(size = 14),
        axis.text = element_text(size = 11),
        legend.position = "bottom",
        legend.text = element_text(size = 11)) +
  labs(x = "Drug",
       y = "Mean score",
       col = "") +
  guides(col = guide_legend(override.aes = list(size = 2.25, alpha = 1))) #Legend: increase size and transparency of points
```

Some interesting points:

+ Heroin and Cocaine are just bad (`r emo::ji("broken")` `r emo::ji("punch")` `r emo::ji("fishing_pole_and_fish")`)...

+ Social harm for alcohol slightly higher than Cocaine `r emo::ji("broken")` 

+ Ketamine has quite high physical harm score `r emo::ji("punch")`

+ I had expected Cannabis' dependence score to be lower `r emo::ji("fishing_pole_and_fish")`

## Conclusion:  

```{r, fig.showtext=TRUE, fig.align='center'}

p1 <- ggplot() +  geom_emoji("pill", color = "blue", size = 50) + geom_fontawesome("fa-ban", color='red', size = 45) + theme_void()

p2 <- ggplot() +  geom_emoji("smoking", color = "black", size = 50) + geom_fontawesome("fa-ban", color='red', size = 45) + theme_void()

p3 <- ggplot() +  geom_emoji("beers", color = "black", size = 50) + geom_fontawesome("fa-ban", color='red', size = 40) + theme_void()

gridExtra::grid.arrange(p1, p2, p3, ncol = 3)
```

**Using emojis was fun, but a little challenging.**^[Short tutorial from early WRUG meeting: https://warwick.ac.uk/fac/sci/wdsi/events/wrug/resources/emoji_plots.pdf] ^[Limitations: https://cran.r-project.org/web/packages/emojifont/vignettes/emojifont.html]