Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in R Programming by (50.2k points)

I know that the color argument inside aes function treats the string as different factors for example

colors = colorRampPalette(c("red","blue"))(3))

#colors is a list of hex code for colors ranging from red to blue

dt = data.table(x=(1,2,3),y=(3,2,1), level=(1,2,3))

ggplot(dt)+geom_point(aes(x=x,y=y,color = colors[level]))

The above code will not use the hex codes as inputs for colors but just different factors. Is there any way the color parameter inside aes can actually use the hex codes? 

1 Answer

0 votes
by (108k points)

In R programming if you use the I(...) function around a field, then by default the ggplot2 package will interprets it as an identity that is the real color, not as a factor.

The correct way is as follows:

colors = colorRampPalette(c("red","blue"))(3)

dt = data.table(x = c(1,2,3), y = c(3,2,1), level = c(1,2,3))

ggplot(dt) +

  geom_point(aes(x = x, y = y, color = I(colors[level])), size = 5)

Browse Categories

...