Reputation: 4879
I want to create a plot where I want to display a mean value and confidence intervals for this mean value. To do so, I am using plotmath
. Here is something I have done that works-
library(ggplot2)
ggplot(mtcars, aes(as.factor(cyl), wt)) + geom_boxplot() +
labs(
title = "Mean weight:",
subtitle = parse(text = paste(
"list(~italic(mu)==", 3.22, ",", "CI[95~'%'] ", "(", 2.87, ",", 3.57, "))",
sep = ""
))
)
Created on 2019-08-25 by the reprex package (v0.3.0)
But this is not what I actually want. The format in which I instead want to display these results is the following-
So there are two things I can't seem to figure out how to do using plotmath
:
95 %
should instead be 95%
Use [
instead of (
How can I do this?
P.S. It is important, for reasons to complicated to explain here, for me to have list
inside the paste
function because I want to save these expressions as a character
-type column in a dataframe. This is why I haven't accepted the two solutions provided below.
Upvotes: 2
Views: 374
Reputation: 7818
This solution keeps list and paste.
library(ggplot2)
ggplot(mtcars, aes(as.factor(cyl), wt)) + geom_boxplot() +
labs(
title = "Mean weight:",
subtitle = parse(text = paste(
"list(~italic(mu)==", 3.22, ",", "CI[95*'%'] ", "*'['*", 2.87, ",", 3.57, "*']')",
sep = ""
))
)
Upvotes: 3
Reputation: 17790
I'll assume that what you actually care about is that the output looks right, not that plotmath is used. You can use the ggtext package I'm currently developing, which gives you the possibility to use simple markdown/HTML inside of ggplot2. I generally find it much easier to create basic math expressions that way than wrangling with plotmath. And you don't have to work with R expressions at all, the input is always a simple character string.
# this requires the current development versions of ggplot2 and ggtext
# remotes::install_github("tidyverse/ggplot2")
# remotes::install_github("clauswilke/ggtext")
library(ggplot2)
library(ggtext)
ggplot(mtcars, aes(as.factor(cyl), wt)) +
geom_boxplot() +
labs(
title = "Mean weight:",
subtitle = "*μ* = 3.22, CI<sub>95%</sub>[2.87, 3.57]"
) +
theme(plot.subtitle = element_markdown())
Created on 2019-12-02 by the reprex package (v0.3.0)
Upvotes: 2
Reputation: 269586
Use the formula shown:
ggplot(mtcars, aes(as.factor(cyl), wt)) + geom_boxplot() +
labs(
title = "Mean weight:",
subtitle = ~italic(mu) == 3.22*', '*"CI"[95*'%']*group('[',2.87*','*3.57,']')
)
Upvotes: 4
Reputation: 887118
An option would be bquote
library(ggplot2)
ggplot(mtcars, aes(as.factor(cyl), wt)) +
geom_boxplot() +
labs(title = "Mean weight:",
subtitle = bquote(italic(mu)~"= 3.22,"~CI[95*'%']~"["*"2.87, 3.57"*"]"))
Upvotes: 3