ChatGPT解决这个技术问题 Extra ChatGPT

Change size of axes title and labels in ggplot2

I have a really simple question, which I am struggling to find the answer to. I hoped someone here might be able to help me.

An example dataframe is presented below:

a <- c(1:10)
b <- c(10:1)
df <- data.frame(a,b)
library(ggplot2)
g = ggplot(data=df) + geom_point(aes(x=a, y=b)) +
  xlab("x axis")
g

I just want to learn how I change the text size of the axes titles and the axes labels.


s
shir

You can change axis text and label size with arguments axis.text= and axis.title= in function theme(). If you need, for example, change only x axis title size, then use axis.title.x=.

g+theme(axis.text=element_text(size=12),
        axis.title=element_text(size=14,face="bold"))

There is good examples about setting of different theme() parameters in ggplot2 page.


There is also a very intuitive function rel() now. e.g. size = rel(2.0)
how would one change the labs(x = "x axis") text size without changing the value of the x axis ticks?
c
chunjiw

I think a better way to do this is to change the base_size argument. It will increase the text sizes consistently.

g + theme_grey(base_size = 22)

As seen here.


If you already have other theme instances, this can cause conflicts.
@AdamErickson Yes so you just add base_size = 22 to your theme of choice..
R
Rtist

If you are creating many graphs, you could be tired of typing for each graph the lines of code controlling for the size of the titles and texts. What I typically do is creating an object (of class "theme" "gg") that defines the desired theme characteristics. You can do that at the beginning of your code.

My_Theme = theme(
  axis.title.x = element_text(size = 16),
  axis.text.x = element_text(size = 14),
  axis.title.y = element_text(size = 16))

Next, all you will have to do is adding My_Theme to your graphs.

g + My_Theme
g1 + My_Theme 

This is the best answer, imo. There won't be many (if any) conflicts with pre-set themes.
I
InterestedInR

To change the size of (almost) all text elements, in one place, and synchronously, rel() is quite efficient:
g+theme(text = element_text(size=rel(3.5))

You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)), strip.text.x = element_text(size=rel(3.5)), strip.text.y = element_text(size=rel(3.5)))