1

I have a fix ggplot object (coming from a nice function that I do not want to touch). However, I would like to add some coloring afterwards, thus add new data. How would that be possible?

Here's a simple example.

gg <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()

Now, I want object gg to be colored by Petal.Length,e.g. something like (but that's not working)

gg_colored <- gg + aes(col=Petal.Length)

to obtain:

enter image description here

2 Answers 2

1

The solution is to work with the way to handle aesthetics programmatically using aes_string or aes_().

The plot can be equally generated with

data(iris)
gg <- ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, col=Petal.Length)) +
geom_point()
gg

Or

data(iris)
gg <- ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width))
gg_colored <- gg + geom_point(aes_string(col="Petal.Length"))
gg_colored
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but that's not what I mean. Please consider gg as a object. I need something like gg + aes(col=Petal.Length)
Ok, now I got it!
0

With the help of paoloeusebi's anwer, I also found a way to add a new colouring variable (instead of Petal.Length which is inside of iris)

mydat <- gg$data 
mydat$col <- rep(LETTERS[1:3], each=50) 
gg_colored <- gg + geom_point(data=mydat, aes_string(col="col"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.