Reputation: 4501
library(tidyverse)
library(ggtext)
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
labs(title = "This is a Title\n") +
theme(plot.title.position = "plot",
plot.title = element_markdown(),
legend.position = "none")
Why can't I add a line break to my ggplot title to get some white space between the title and panel? I know there's other ways to achieve this padding, but I want to limit this question explicitly to line break methods for adding white space.
I'm almost certain I've done this before for axis titles to add white space between the axis title and plot panel. Why won't \n
work in the plot title?
Edit with additional information based on comments
This code chunk will break a title into two lines.
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
labs(title = "Line Number One\nLine Number Two") +
theme(plot.title.position = "plot",
legend.position = "none")
This "almost identical" code chunk won't. The big question... Why? I imagine in Markdown I need the <br>
or maybe two spaces? to break the line?
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
labs(title = "The First Line\nThe Second Line") +
theme(plot.title.position = "plot",
plot.title = element_markdown(),
legend.position = "none")
Upvotes: 6
Views: 9015
Reputation: 4501
I went with the simplest solution to add two spaces prior to the \n
, and I also needed to add a non-breaking space after the line break to get the padding:
library(tidyverse)
library(ggtext)
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
labs(title = "This is a Title \n ") +
theme(plot.title.position = "plot",
plot.title = element_markdown(),
legend.position = "none")
Upvotes: 0
Reputation: 84709
You can use two spaces followed by 'Return':
library(ggplot2)
library(ggtext)
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
labs(title = "This is a Title
This is a new line
") +
theme(plot.title.position = "plot",
plot.title = element_markdown(),
legend.position = "none")
title = "This is a Title \r\nThis is a new line"
works as well.
Upvotes: 1
Reputation: 50738
Yes.
ggtext
Use <br>
library(tidyverse)
library(ggtext)
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
labs(title = "This is a Title<br>Another line") +
theme(plot.title.position = "plot",
plot.title = element_markdown(),
legend.position = "none")
The nice thing with ggtext
is that you can use a lot of markdown/HTML syntax to highlight/colour/theme text in ggplot2
titles & labels.
ggplot2
Use \n
library(tidyverse)
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
labs(title = "This is a Title\nAnother line") +
theme(plot.title.position = "plot",
legend.position = "none")
Upvotes: 11