Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modifying ggplot objects after creation

Tags:

Is there a preferred way to modify ggplot objects after creation?

For example I recommend my students to save the r object together with the pdf file for later changes...

library(ggplot2) graph <-    ggplot(mtcars, aes(x=mpg, y=qsec, fill=cyl)) +   geom_point() +   geom_text(aes(label=rownames(mtcars))) +   xlab('miles per galon') +   ggtitle('my title')  ggsave('test.pdf', graph) save(graph, file='graph.RData') 

So new, in case they have to change title or labels or sometimes other things, they can easily load the object and change simple things.

load('graph.RData') print(graph) graph +    ggtitle('better title') +   ylab('seconds per quarter mile') 

What do I have to do for example to change the colour to discrete scale? In the original plot I would wrap the y in as.factor. But is there a way to do it afterwards? Or is there a better way on modifying the objects, when the data is gone. Would love to get some advice.

like image 954
drmariod Avatar asked Jan 30 '17 15:01

drmariod


People also ask

What operator allows you to keep adding layers to a Ggplot () object?

Elements that are normally added to a ggplot with operator + , such as scales, themes, aesthetics can be replaced with the %+% operator. The situation with layers is different as a plot may contain multiple layers and layers are nameless. With layers %+% is not a replacement operator.

Does Ggplot only work with data frames?

ggplot only works with data frames, so we need to convert this matrix into data frame form, with one measurement in each row. We can convert to this “long” form with the melt function in the library reshape2 . Notice how ggplot is able to use either numerical or categorical (factor) data as x and y coordinates.

Can you filter within Ggplot?

ggplot2 allows you to do data manipulation, such as filtering or slicing, within the data argument.


1 Answers

You could use ggplot_build() to alter the plot without the code or data:

Example plot:

data("iris")  p <- ggplot(iris) +    aes(x = Sepal.Length, y = Sepal.Width, colour = Species) +    geom_point() 

Colours are respective to Species.

Disassemble the plot using ggplot_build():

q <- ggplot_build(p) 

Take a look at the object q to see what is happening here. To change the colour of the point, you can alter the respective table in q:

q$data[[1]]$colour <- "black" 

Reassemble the plot using ggplot_gtable():

q <- ggplot_gtable(q) 

And plot it:

plot(q) 

Now, the points are black.

like image 97
ottlngr Avatar answered Sep 28 '22 09:09

ottlngr