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,
can ggplot handle such cases?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With