americo
americo

Reputation: 1063

Why is the plot title not scaled correctly when scaling the text size with theme(text = element_text())?

I'm creating a chart that shows two box plots side by side, and I'm trying to scale the text inside the plot, which is giving me issues. I have the problem solved, so I guess now I'm just trying to understand what is going on in the background.

The data can be downloaded here. (42 MB)

A very basic plot:

ggplot(perdiffm, aes(variable, value)) + stat_boxplot(geom = 'errorbar') + geom_boxplot()

enter image description here

Now a plot with proper labels and text size:

ggplot(perdiffm, aes(variable, value)) + stat_boxplot(geom = 'errorbar') + geom_boxplot() + scale_x_discrete(labels = c('% Difference A', '% Difference B')) + labs(title = "Percent difference between meters", y = '% Difference') + theme(text = element_text(size = rel(5)), axis.title.x = element_blank(), panel.grid.major.x = element_blank())

enter image description here

Notice the plot title!! I don't understand why that happens, but here is my solution:

ggplot(perdiffm, aes(variable, value)) + stat_boxplot(geom = 'errorbar') + geom_boxplot() + scale_x_discrete(labels = c('% Difference A', '% Difference B')) + labs(title = "Percent difference between meters", y = '% Difference') + theme(text = element_text(size = 20), axis.title.x = element_blank(), panel.grid.major.x = element_blank())

Basically just changed text_element(size = rel(5)) to text_element(size = 20) (As suggested by Roland)

enter image description here

So my question is: Why do I have to explicitly code the text size of the title??? Why doesn't text = element_text(size = rel(5)) not work with the title? (Two questions I guess but they pretty much ask the same thing)

Please let me know if I'm doing something wrong (very likely) and how to avoid it in the future.

Thanks!

Upvotes: 0

Views: 263

Answers (1)

Roland
Roland

Reputation: 132959

According to the documentation plot.title inherits from title which inherits from text. So this seems like a bug.

The canonical way to increase the size of all text is setting the base size in the theme. This preserves the relative text size of all elements.

A plot (without downloading your big dataset, which is unrelated to your question):

p <- ggplot(mtcars, aes(factor(cyl), mpg))

p + 
  geom_boxplot() + 
  ggtitle("Boxplot")

enter image description here

Increasing the base size:

p + 
  geom_boxplot() + 
  ggtitle("Boxplot") +
  theme_grey(base_size = 20) #default is 12

enter image description here

Upvotes: 1

Related Questions