2016-02-08 37 views
4

這是我的第一個問題,希望有人能幫我解答。指定點顏色取決於data.frame列值R

我從R以CSV data<-read.csv("/data.csv")讀取數據和得到的東西,如:

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

每組顏色可能會有所不同,它們是由時產生的csv文件如下公式分配,但這些都是所有可能的顏色(組數也可能不同)。

我一直在嘗試使用ggplot()像這樣:

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

一切除了顏色正確

  • 小繪製藍色
  • 中繪製紅色
  • 其他被畫成綠色
  • 大被畫成黃色

我注意到右側的圖例按字母順序排列組(大,中,其他,小),但顏色保持csv文件順序。

下面是情節的截圖。

enter image description here

誰能告訴我缺少了什麼在我的代碼,以解決這一問題?其他方法來達到同樣的結果是受歡迎的。要做到這一點

回答

6

的一種方式,通過help("scale_colour_manual")建議是使用指定的字符向量:

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

然後規模的values參數映射到此矢量

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

全碼

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

輸出:

enter image description here

數據

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

完美!你介意添加最終的代碼嗎?我會接受你的回答:) – gantonioid