Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color points with the color as a column in ggplot2 [duplicate]

Tags:

r

ggplot2

I have a dataframe where a color is given for each point in a column:

d<-data.frame(x=1:10,y=1:10,col=c(rep("red",n=5),rep("green",n=5)))
d$col<-as.character(d$col)
ggplot(data=d,aes(x=x,y=y,colour=col))+geom_point()

As you can see, the colour is not interpreted as a colour, but a group,

enter image description here

can ggplot handle such cases?

like image 685
Xavier Prudent Avatar asked Mar 30 '17 22:03

Xavier Prudent


1 Answers

This question has probably been asked and answered before. However, there is another issue in setting up the data.

The OP is creating the data by

d <- data.frame(x = 1:10,
                y = 1:10,
                col = c(rep("red", n = 5), rep("green", n = 5)))

This results in an alternation of the two colours

d
#    x  y   col
#1   1  1   red
#2   2  2 green
#3   3  3   red
#4   4  4 green
#5   5  5   red
#6   6  6 green
#7   7  7   red
#8   8  8 green
#9   9  9   red
#10 10 10 green 

Reason is that n is not a defined parameter to the rep() function. According to ?rep, valid parameters are times, lenght.out, and each.

Probably, the OP has meant

d <- data.frame(x = 1:10,
                y = 1:10,
                col = c(rep("red", 5), rep("green", 5)))

which results in successive rows being coloured in the same colour:

d
#    x  y   col
#1   1  1   red
#2   2  2   red
#3   3  3   red
#4   4  4   red
#5   5  5   red
#6   6  6 green
#7   7  7 green
#8   8  8 green
#9   9  9 green
#10 10 10 green

By the way,

col = c(rep("red", 5), rep("green", 5))

can be written more clearly as

col = rep(c("red", "green"), each = 5)

With this, the following plot statements

library(ggplot2)
# variant 1 (OP's own answer)
ggplot(data = d, aes(x = x, y = y)) + geom_point(colour = d$col)
# variant 2 (aosmith' comment, more "ggplot2-like")
ggplot(data = d, aes(x = x, y = y, colour = col)) + geom_point() + 
  scale_colour_identity()

produce the same chart:

enter image description here

like image 80
Uwe Avatar answered Oct 13 '22 01:10

Uwe