panuffel
panuffel

Reputation: 684

ggplot2: Add coloring to a fix ggplot object

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

Upvotes: 1

Views: 53

Answers (2)

panuffel
panuffel

Reputation: 684

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"))

Upvotes: 0

paoloeusebi
paoloeusebi

Reputation: 1086

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

Upvotes: 1

Related Questions