Skip to content

Instantly share code, notes, and snippets.

@antunderwood
Created September 12, 2020 09:07
Show Gist options
  • Save antunderwood/ce4e4834a93a9faa9e14ecfee1b396da to your computer and use it in GitHub Desktop.
Save antunderwood/ce4e4834a93a9faa9e14ecfee1b396da to your computer and use it in GitHub Desktop.
Code to plot stacked charts for AST and AMR loci
---
title: "Plotting stacked AST/AMR data"
output: html_notebook
---
Read in some data. I've used JSON so I can have the data in this text file
```{r message=FALSE, warning=FALSE}
library(jsonlite)
ast_gene_json <- '[
{
"id": "sample1",
"Drug1": "S",
"Drug2": "R",
"Drug3": "R",
"Carbapenamases": "Gene1"
},
{
"id": "sample2",
"Drug1": "S",
"Drug2": "R",
"Drug3": "R",
"Carbapenamases": "Gene1"
},
{
"id": "sample3",
"Drug1": "S",
"Drug2": "R",
"Drug3": "R",
"Carbapenamases": "Gene2"
},
{
"id": "sample4",
"Drug1": "R",
"Drug2": "R",
"Drug3": "R",
"Carbapenamases": "Gene3"
},
{
"id": "sample5",
"Drug1": "R",
"Drug2": "R",
"Drug3": "R",
"Carbapenamases": "Gene3"
},
{
"id": "sample6",
"Drug1": "R",
"Drug2": "R",
"Drug3": "R",
"Carbapenamases": "Gene1, Gene2"
},
{
"id": "sample7",
"Drug1": "R",
"Drug2": "R",
"Drug3": "S",
"Carbapenamases": "Gene4"
},
{
"id": "sample8",
"Drug1": "R",
"Drug2": "R",
"Drug3": "S",
"Carbapenamases": "Gene5"
},
{
"id": "sample9",
"Drug1": "R",
"Drug2": "R",
"Drug3": "S",
"Carbapenamases": "Gene6, Gene 7"
},
{
"id": "sample10",
"Drug1": "R",
"Drug2": "R",
"Drug3": "S",
"Carbapenamases": "Gene5"
}
]'
ast_genes <- jsonlite::fromJSON(ast_gene_json)
```
Count numbers of occurences
```{r message=FALSE, warning=FALSE}
library(dplyr)
drug_3_counts <- ast_genes %>% count(Drug3,Carbapenamases, name = "count")
```
Plot stacked data.
Use the fct_relevel function from the forcats library so that S comes before R
```{r message=FALSE, warning=FALSE}
library(forcats)
library(ggplot2)
drug_3_counts %>%
mutate(Drug3 = fct_relevel(Drug3, "S", "R")) %>%
ggplot(aes(x = Drug3, y = count , fill = Carbapenamases)) +
geom_bar(stat="identity")
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment