Using Italic() with a Variable in Ggplot2 Title Expression

Using italic() with a variable in ggplot2 title expression

bquote or substitute should work,

 a = 'text' 
plot(1,1, main=bquote(italic(.(a))))
plot(1,1, main=substitute(italic(x), list(x=a)))

How to add a complex label with italics and a variable to ggplot?

You could use annotate() which allows you to paste directly into the plot.

library(ggplot2)
ggplot(data=df, aes(x=x, y=y)) +
geom_point(color="black") +
annotate('text', 2.5, 4,
label=paste("italic(y)==", a, "+", b,
"~italic(x)~';'~italic(r)^2==", r2),
parse=TRUE,
hjust=1, size=5)

Yields:

Sample Image

Data:

df <- data.frame(x=c(1:5), y=c(1:5))
a <- 1
b <- 2
r2 <- 0.9

ggplot: italicize part of dynamically generated title

You can use bquote for this. Inside bquote, expressions wrapped in .() will be evaluated.

p = list()
for (i in seq_along(title_list)) {
p[[i]] = ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
labs(title = bquote(italic(.(title_list[i])) ~ .(title_suffix)))
}

gridExtra::grid.arrange(p[[1]], p[[2]], p[[3]])

Sample Image

A very related question is this one.

R ggplot2 using italics and non-italics in the same category label

You can make a vector of expressions, and apply it to the labels argument in scale_x_discrete:

labs <- sapply(
strsplit(as.character(data$name), " "),
function(x) parse(text = paste0("italic('", x[1], "')~", x[2]))
)

ggplot(data, aes(name, value)) +
geom_col() + coord_flip() +
scale_x_discrete(labels = labs)

Sample Image

If you have spaces in your labels e.g. OTU 100, you may want to substitute a tilde for the space, e.g. OTU~100.

Italics within plotmath expression cannot be rendered bold in ggplot

expression(bold("% of group ")*bolditalic("n"))

ggplot fails to put numbers in italic in facet title

Update after clarification:

library(ggplot2)
library(tibble)
tibble(
a = c("italic('a1a1')", 'Not~Italic'),
x = c(1,1),
y = c(1,1)
) %>%
ggplot(aes(x,y)) +
geom_point() +
facet_grid(a~., labeller = label_parsed) +
theme(
strip.text = element_text(size = 20)
) +
xlab(expression(italic(Italic~part~of~label1)~not~italic~part~of~label1))

Sample Image

First answer:
Here is how we could do it using element_text():

library(ggplot2)
library(tibble)

tibble(
a = 'a1a1',
x = 1,
y = 1
) %>%
ggplot(aes(x,y)) +
geom_point() +
facet_grid(a~.)+
theme(
strip.text.y = element_text(
size = 12, face = "italic")
)

Sample Image

How to italicize part (one or two words) of x-axis labels using multiple lines

You can cheat using atop:

my_x_titles <- c(
expression(atop(paste("4 cylinders"), (italic(N) == 11))),
expression(atop(paste("6 cylinders"), (italic(N) == 7))),
expression(atop(paste("8 cylinders"), (italic(N) == 14)))
)

base + scale_x_discrete(breaks = c(4, 6, 8),
labels = my_x_titles)


Related Topics



Leave a reply



Submit