Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change size from specific geom in ggplot2?

Tags:

r

ggplot2

I have a ggplot containing 2 layers geom_point and geom_line as shown below.

gp <- ggplot(data = mtcars , aes(x = disp , y = hp)) + 
       geom_point(size = 3) + geom_line(size = 1 , color = "red")

`

Once the plot created, inside the gp, I want to change the size of only one geom (e.g line). How can I do that ?

like image 202
Chirag Avatar asked Jan 26 '23 12:01

Chirag


2 Answers

If you wish to replace the existing size with a smaller one (or replace a solid linetype with a dashed one, a filled shape with an unfilled one, etc.), overlaying may not have the best visual effect. As an alternative, you can dig into the specific layer of the ggplot object you've created, & manually change the parameters there.

(Note that this requires you to know the order of geom layers in the object.)

gp$layers[[2]]$aes_params$size <- 0.5 # change the size of the geom_line layer from 1 to 0.5
gp$layers[[1]]$aes_params$size <- 1   # change the size of the geom_point layer from 3 to 1

plot

I assume your use case involves modifying a ggplot object outputted by some package's plotting function? Otherwise, it's probably simpler to specify the desired parameters at the point of plot creation...

like image 142
Z.Lin Avatar answered Feb 07 '23 09:02

Z.Lin


You can override specific properties of the plot keeping rest of them as it is

library(ggplot2)
gp + geom_point(size = 5)

enter image description here

Or with geom_line

gp + geom_line(size = 5, color = "red")

enter image description here

like image 42
Ronak Shah Avatar answered Feb 07 '23 09:02

Ronak Shah