Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change font size of labels without knowing labels in ggplot2

Tags:

r

ggplot2

r-grid

I would like to change the font size of the labels in this plot:

library(ggplot2)
p <- ggplot(mtcars, aes(x=wt, y=mpg)) + 
        geom_text(label=rownames(mtcars))
p

mtcars plot

My problem: I do not know what the labels are. (I stored a plot in which I used different data.frame()s to add geom_text(). I now only loaded the plot (p in this example), but do not want to also load the data.frame()s with which I created the labels).

As I do not know what the labels are, I cannot use this solution:

p + geom_text(label=rownames(mtcars), size=2)

(Another problem with this solution would be that I still needed to delete the original geom_text() with the larger font-size).


I can change the size of all text in the plot with this solution:

library(grid)    
grid.force()
grid.gedit("GRID.text", grep=TRUE, gp=gpar(fontsize=4.5))

However, now also my axes changed, which is not what I wanted.


I believe there are several options to achieve what I want, at least two of which should be fairly simply to implement:

  1. Save the object from grid.gedit() to p1 and then p1 + theme(text = element_text(size=2)). My problem here: I do not know how to save the object from grid.gedit(). This would be my preferred option.

  2. Go to the right viewport before applying grid.gedit(). I tried this, but still change both the labels (which I want) and the axes text (which I do not want).

  3. Somehow extract the data.frame for the labels from the stored plot (p in this example) to apply the solution that I provided first.

like image 363
Flo Avatar asked Nov 27 '25 07:11

Flo


1 Answers

You can inspect (/modify) the plot after building it,

library(ggplot2)
p <- ggplot(mtcars, aes(x=wt, y=mpg)) + 
  geom_text(label=rownames(mtcars))

g <- ggplot_build(p)
# original data is in str(g$plot$data)

# but it's easier to process the data for rendering
g[["data"]][[1]][["size"]] <- 5
g[["data"]][[1]][["colour"]] <- "red"

gg <- ggplot_gtable(g)
grid.newpage()
grid.draw(gg)

enter image description here

like image 95
baptiste Avatar answered Nov 29 '25 19:11

baptiste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!