SlideShare a Scribd company logo
1 of 33
Spruce up your ggplot2 visualizations
with formatted text
Claus O. Wilke
The University of Texas at Austin
https://wilkelab.org/ggtext
@clauswilke clauswilke
A common problem:
Mixing italics and normal text in ggplot
https://stackoverflow.com/questions/39282293/r-ggplot2-using-italics-and-non-italics-in-the-same-category-label
bactname OTUname name value
Staphylococcaceae OTU 1 Staphylococcaceae (OTU 1) -0.5
Moraxella OTU 2 Moraxella (OTU 2) 0.5
Streptococcus OTU 3 Streptococcus (OTU 3) 2.0
Acinetobacter OTU 4 Acinetobacter (OTU 4) 3.0
bactname OTUname name value
Staphylococcaceae OTU 1 Staphylococcaceae (OTU 1) -0.5
Moraxella OTU 2 Moraxella (OTU 2) 0.5
Streptococcus OTU 3 Streptococcus (OTU 3) 2.0
Acinetobacter OTU 4 Acinetobacter (OTU 4) 3.0
data %>%
ggplot(aes(name, value)) +
geom_col() + coord_flip()
bactname OTUname name value
Staphylococcaceae OTU 1 Staphylococcaceae (OTU 1) -0.5
Moraxella OTU 2 Moraxella (OTU 2) 0.5
Streptococcus OTU 3 Streptococcus (OTU 3) 2.0
Acinetobacter OTU 4 Acinetobacter (OTU 4) 3.0
data %>%
ggplot(aes(name, value)) +
geom_col() + coord_flip()
https://stackoverflow.com/questions/39282293/r-ggplot2-using-italics-and-non-italics-in-the-same-category-label
How should we specify formatted text?
data %>%
ggplot(aes(name, value)) +
geom_col() + coord_flip() +
ggtitle("species names are *in italics*")
data %>%
ggplot(aes(name, value)) +
geom_col() + coord_flip() +
ggtitle("species names are *in italics*")
library(ggtext) # remotes::install_github('wilkelab/ggtext')
data %>%
ggplot(aes(name, value)) +
geom_col() + coord_flip() +
ggtitle("species names are *in italics*") +
theme(plot.title = element_markdown())
library(ggtext) # remotes::install_github('wilkelab/ggtext')
data %>% mutate(
name = glue("*{bactname}* ({OTUname})") # library(glue)
)
data %>% mutate(
name = glue("*{bactname}* ({OTUname})") # library(glue)
)
bactname OTUname name value
Staphylococcaceae OTU 1 *Staphylococcaceae* (OTU 1) -0.5
Moraxella OTU 2 *Moraxella* (OTU 2) 0.5
Streptococcus OTU 3 *Streptococcus* (OTU 3) 2.0
Acinetobacter OTU 4 *Acinetobacter* (OTU 4) 3.0
data %>% mutate(
name = glue("*{bactname}* ({OTUname})")
) %>%
ggplot(aes(name, value)) +
geom_col() + coord_flip() +
theme(axis.text.y = element_markdown())
Your plots are boring.
Don’t you ever use color?
data %>% mutate(
color = c("#009E73", "#D55E00", "#0072B2", "#000000"),
name = glue("<i style='color:{color}'>{bactname}</i> ({OTUname})")
) %>%
data %>% mutate(
color = c("#009E73", "#D55E00", "#0072B2", "#000000"),
name = glue("<i style='color:{color}'>{bactname}</i> ({OTUname})")
) %>%
ggplot(aes(name, value, fill = color)) +
geom_col(alpha = 0.5) + coord_flip() +
scale_fill_identity() +
theme(axis.text.y = element_markdown())
What else can you do?
https://stackoverflow.com/questions/14070953/photo-
alignment-with-graph-in-r/30765590#30765590
labels <- c(
Interphase = "<img src='img/interphase.jpg' width='50' /><br>Interphase",
Prophase = "<img src='img/prophase.jpg' width='50' /><br>Prophase",
Metaphase = "<img src='img/metaphase.jpg' width='50' /><br>Metaphase",
Anaphase = "<img src='img/anaphase.jpg' width='50' /><br>Anaphase",
Telophase = "<img src='img/telophase.jpg' width='50' /><br>Telophase"
)
https://stackoverflow.com/questions/14070953/photo-
alignment-with-graph-in-r/30765590#30765590
https://stackoverflow.com/questions/14070953/photo-
alignment-with-graph-in-r/30765590#30765590
labels <- c(
Interphase = "<img src='img/interphase.jpg' width='50' /><br>Interphase",
...
)
ggplot(data, aes(phase, value, fill = cat)) +
geom_col(position = "dodge") +
scale_x_discrete(name = NULL, labels = labels) +
theme(axis.text.x = element_markdown(lineheight = 1.2))
https://stackoverflow.com/questions/14070953/photo-
alignment-with-graph-in-r/30765590#30765590
labels <- c(
Interphase = "<img src='img/interphase.jpg' width='50' /><br>Interphase",
...
)
ggplot(data, aes(phase, value, fill = cat)) +
geom_col(position = "dodge") +
scale_x_discrete(name = NULL, labels = labels) +
theme(axis.text.x = element_markdown(lineheight = 1.2))
Text boxes, backgrounds, and word-wrapping
https://wilkelab.org/ggtext
Does this only work for theme elements?
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point() + geom_smooth(method = "lm") +
facet_wrap(~Species)
iris_cor <- iris %>%
group_by(Species) %>%
summarize(r_square = cor(Sepal.Length, Sepal.Width)^2)
iris_cor
#> # A tibble: 3 x 2
#> Species r_square
#> <fct> <dbl>
#> 1 setosa 0.551
#> 2 versicolor 0.277
#> 3 virginica 0.209
iris_cor <- iris %>%
group_by(Species) %>%
summarize(r_square = cor(Sepal.Length, Sepal.Width)^2) %>%
mutate(
Sepal.Length = 8,
Sepal.Width = 4.5,
label = glue("*r*<sup>2</sup> = {round(r_square, 2)}")
)
iris_cor
#> # A tibble: 3 x 5
#> Species r_square Sepal.Length Sepal.Width label
#> <fct> <dbl> <dbl> <dbl> <glue>
#> 1 setosa 0.551 8 4.5 *r*<sup>2</sup> = 0.55
#> 2 versicolor 0.277 8 4.5 *r*<sup>2</sup> = 0.28
#> 3 virginica 0.209 8 4.5 *r*<sup>2</sup> = 0.21
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point() + geom_smooth(method = "lm") +
geom_richtext(
data = iris_cor, aes(label = label),
hjust = 1, vjust = 1
) +
facet_wrap(~Species)
The package that makes it all possible
text <- "Some text **in bold.**"
gp <- grid::gpar(
fontfamily = "Comic Sans MS", fontsize = 20, col = "blue"
)
g1 <- grid::textGrob(text, 0.1, 0.7, hjust = 0, gp = gp)
grid::grid.draw(g1)
text <- "Some text **in bold.**"
gp <- grid::gpar(
fontfamily = "Comic Sans MS", fontsize = 20, col = "blue"
)
g1 <- grid::textGrob(text, 0.1, 0.7, hjust = 0, gp = gp)
g2 <- gridtext::richtext_grob(text, 0.1, 0.4, hjust = 0, gp = gp)
grid::grid.draw(g1)
grid::grid.draw(g2)
https://wilkelab.org/ggtext
https://wilkelab.org/gridtext
@clauswilke
clauswilke

More Related Content

What's hot

Amyotrophic lateral sclerosis (als)
Amyotrophic lateral sclerosis (als)Amyotrophic lateral sclerosis (als)
Amyotrophic lateral sclerosis (als)
Jessica González
 
CARDIO- RENAL SYNDROME
CARDIO- RENAL SYNDROMECARDIO- RENAL SYNDROME
CARDIO- RENAL SYNDROME
vishwanath69
 

What's hot (20)

Sle
SleSle
Sle
 
Multiple sclerosis CASE PRESENTATION
Multiple sclerosis CASE PRESENTATIONMultiple sclerosis CASE PRESENTATION
Multiple sclerosis CASE PRESENTATION
 
Neuromuscular Diseases medicine Seminar.pptx
Neuromuscular Diseases medicine Seminar.pptxNeuromuscular Diseases medicine Seminar.pptx
Neuromuscular Diseases medicine Seminar.pptx
 
Amyotrophic lateral sclerosis (als)
Amyotrophic lateral sclerosis (als)Amyotrophic lateral sclerosis (als)
Amyotrophic lateral sclerosis (als)
 
Motor Neuron Disease
Motor Neuron DiseaseMotor Neuron Disease
Motor Neuron Disease
 
Diabetes mellitus, musculoskeletal manifestations
Diabetes mellitus, musculoskeletal manifestationsDiabetes mellitus, musculoskeletal manifestations
Diabetes mellitus, musculoskeletal manifestations
 
Motor neuron disease
Motor neuron diseaseMotor neuron disease
Motor neuron disease
 
Motor neuron disease
Motor neuron diseaseMotor neuron disease
Motor neuron disease
 
Metabolic syndrome: an Asian perspective
Metabolic syndrome: an Asian perspectiveMetabolic syndrome: an Asian perspective
Metabolic syndrome: an Asian perspective
 
Diabetic Microvascular Complications
Diabetic  Microvascular  ComplicationsDiabetic  Microvascular  Complications
Diabetic Microvascular Complications
 
Insulin basics.p
Insulin basics.pInsulin basics.p
Insulin basics.p
 
CARDIO- RENAL SYNDROME
CARDIO- RENAL SYNDROMECARDIO- RENAL SYNDROME
CARDIO- RENAL SYNDROME
 
Approach to muscle weakness
Approach to muscle weaknessApproach to muscle weakness
Approach to muscle weakness
 
Improving end of life care in neurological disease
Improving end of life care in neurological diseaseImproving end of life care in neurological disease
Improving end of life care in neurological disease
 
Rheumatology Tutorial
Rheumatology TutorialRheumatology Tutorial
Rheumatology Tutorial
 
Multiple sclerosis
Multiple sclerosisMultiple sclerosis
Multiple sclerosis
 
Approach to a patient with peripheral neuropathy
Approach to a patient with peripheral neuropathyApproach to a patient with peripheral neuropathy
Approach to a patient with peripheral neuropathy
 
A Case of CIDP
A Case of CIDPA Case of CIDP
A Case of CIDP
 
Hypertension
HypertensionHypertension
Hypertension
 
Steroid Myopathy
Steroid Myopathy Steroid Myopathy
Steroid Myopathy
 

Similar to Spruce up your ggplot2 visualizations with formatted text

Open Access In Medicine
Open Access In MedicineOpen Access In Medicine
Open Access In Medicine
Martin Fenner
 
Mobile Number Portability - The Process Factory
Mobile Number Portability - The Process FactoryMobile Number Portability - The Process Factory
Mobile Number Portability - The Process Factory
BSP Media Group
 
Assessing the impact of transposable element variation on mouse phenotypes an...
Assessing the impact of transposable element variation on mouse phenotypes an...Assessing the impact of transposable element variation on mouse phenotypes an...
Assessing the impact of transposable element variation on mouse phenotypes an...
Thomas Keane
 
Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)
brian d foy
 
Connectix webserver
Connectix webserverConnectix webserver
Connectix webserver
steveheer
 
Connectix webserver
Connectix webserverConnectix webserver
Connectix webserver
steveheer
 
การสื่อสารข้อมูลทางคอมพิวเตอร์
การสื่อสารข้อมูลทางคอมพิวเตอร์การสื่อสารข้อมูลทางคอมพิวเตอร์
การสื่อสารข้อมูลทางคอมพิวเตอร์
chukiat008
 

Similar to Spruce up your ggplot2 visualizations with formatted text (20)

Tests in vitro de l'action inhibitrice de la croissance de P. falciparum par ...
Tests in vitro de l'action inhibitrice de la croissance de P. falciparum par ...Tests in vitro de l'action inhibitrice de la croissance de P. falciparum par ...
Tests in vitro de l'action inhibitrice de la croissance de P. falciparum par ...
 
Open Access In Medicine
Open Access In MedicineOpen Access In Medicine
Open Access In Medicine
 
Into Clojure
Into ClojureInto Clojure
Into Clojure
 
Mobile Number Portability - The Process Factory
Mobile Number Portability - The Process FactoryMobile Number Portability - The Process Factory
Mobile Number Portability - The Process Factory
 
Ruby things
Ruby thingsRuby things
Ruby things
 
ICSE-DAPSE 2013 talk
ICSE-DAPSE 2013 talkICSE-DAPSE 2013 talk
ICSE-DAPSE 2013 talk
 
令和から本気出す
令和から本気出す令和から本気出す
令和から本気出す
 
Introducing Security Access Control Policies into Legacy Business Processes
Introducing Security Access Control Policies into Legacy Business ProcessesIntroducing Security Access Control Policies into Legacy Business Processes
Introducing Security Access Control Policies into Legacy Business Processes
 
R programming language
R programming languageR programming language
R programming language
 
01_introduction_lab.pdf
01_introduction_lab.pdf01_introduction_lab.pdf
01_introduction_lab.pdf
 
Assessing the impact of transposable element variation on mouse phenotypes an...
Assessing the impact of transposable element variation on mouse phenotypes an...Assessing the impact of transposable element variation on mouse phenotypes an...
Assessing the impact of transposable element variation on mouse phenotypes an...
 
Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)
 
An Exploration of the Formal Properties of PromQL
An Exploration of the Formal Properties of PromQLAn Exploration of the Formal Properties of PromQL
An Exploration of the Formal Properties of PromQL
 
Data Science for Folks Without (or With!) a Ph.D.
Data Science for Folks Without (or With!) a Ph.D.Data Science for Folks Without (or With!) a Ph.D.
Data Science for Folks Without (or With!) a Ph.D.
 
Science Fiction Sensor Networks
Science Fiction Sensor NetworksScience Fiction Sensor Networks
Science Fiction Sensor Networks
 
名古屋Ruby会議01 - Rubyでライフハッキング10連発♪
名古屋Ruby会議01 - Rubyでライフハッキング10連発♪名古屋Ruby会議01 - Rubyでライフハッキング10連発♪
名古屋Ruby会議01 - Rubyでライフハッキング10連発♪
 
Connectix webserver
Connectix webserverConnectix webserver
Connectix webserver
 
Connectix webserver
Connectix webserverConnectix webserver
Connectix webserver
 
Carnet des innovations 20 fev 2012
Carnet des innovations 20 fev 2012Carnet des innovations 20 fev 2012
Carnet des innovations 20 fev 2012
 
การสื่อสารข้อมูลทางคอมพิวเตอร์
การสื่อสารข้อมูลทางคอมพิวเตอร์การสื่อสารข้อมูลทางคอมพิวเตอร์
การสื่อสารข้อมูลทางคอมพิวเตอร์
 

Recently uploaded

Microsoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdfMicrosoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdf
Overkill Security
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 

Recently uploaded (20)

Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
Microsoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdfMicrosoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdf
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
 

Spruce up your ggplot2 visualizations with formatted text