Assign a point color based on the value of the data.frame R column

This is my first question about SO, I hope someone can help me answer it.

I am reading data from csv with R using data<-read.csv("/data.csv") and getting something like:

 Group xy size Color Medium 1 2 2000 yellow Small -1 2 1000 red Large 2 -1 4000 green Other -1 -1 2500 blue 

Each group color can change, they are assigned by the formula when creating the csv file, but these are all possible colors (the number of groups can also change).

I am trying to use ggplot() as follows:

 data<-read.csv("data.csv") xlim<-max(c(abs(min(data$x)),abs(max(data$x)))) ylim<-max(c(abs(min(data$y)),abs(max(data$y)))) data$Color<-as.character(data$Color) print(data) ggplot(data, aes(x = x, y = y, label = Group)) + geom_point(aes(size = size, colour = Group), show.legend = TRUE) + scale_color_manual(values=c(data$Color)) + geom_text(size = 4) + scale_size(range = c(5,15)) + scale_x_continuous(name="x", limits=c(xlim*-1-1,xlim+1))+ scale_y_continuous(name="y", limits=c(ylim*-1-1,ylim+1))+ theme_bw() 

All right except for the colors

  • Little blue.
  • The tool is painted in red
  • The other is green.
  • Large is painted in yellow.

I noticed that the legend correctly arranges groups alphabetically (Large, Medium, Other, Small), but the colors remain in csv order.

Here is a screenshot of the plot.

enter image description here

Can someone tell me what is missing in my code to fix this? other approaches to achieve the same result are welcome.

+5
source share
1 answer

One way to do this, as help("scale_colour_manual") suggested, is to use a named character character:

 col <- as.character(data$Color) names(col) <- as.character(data$Group) 

And then map the scale values argument to this vector

 # just showing the relevant line scale_color_manual(values=col) + 

full code

 xlim<-max(c(abs(min(data$x)),abs(max(data$x)))) ylim<-max(c(abs(min(data$y)),abs(max(data$y)))) col <- as.character(data$Color) names(col) <- as.character(data$Group) ggplot(data, aes(x = x, y = y, label = Group)) + geom_point(aes(size = size, colour = Group), show.legend = TRUE) + scale_color_manual(values=col) + geom_text(size = 4) + scale_size(range = c(5,15)) + scale_x_continuous(name="x", limits=c(xlim*-1-1,xlim+1))+ scale_y_continuous(name="y", limits=c(ylim*-1-1,ylim+1))+ theme_bw() 

Ouput:

enter image description here

Data

 data <- read.table("Group xy size Color Medium 1 2 2000 yellow Small -1 2 1000 red Large 2 -1 4000 green Other -1 -1 2500 blue",head=TRUE) 
+7
source

Source: https://habr.com/ru/post/1242567/


All Articles