2016-12-07 32 views
0

這是我遇到的問題是什麼:GGPLOT2未檢測GEOM映射與aes_string

library(ggplot2) 
Name1 <- "example withspace" 
df1 <- data.frame(x=1, y=2) 
ggplot() + 
    geom_point(data=df1, mapping=aes_string(x="x", y="y", color=as.name(Name1)), 
    size = 3) + 
    scale_color_manual(values = setNames("red", 
    as.name(Name1))) 

當你運行它,你就會得到:

Error in eval(expr, envir, enclos) : object 'example withspace' not found 

如何格式化scale_color_manual值這樣它會識別名稱中有空格的圖層?

我需要保持這種格式,因爲我的實際代碼有多個圖層。

+1

你想做什麼?你在'df1'中沒有一個名爲'withspace'的變量,所以沒有什麼可以映射的。無論如何,你可能不希望帶空格的變量名;你將不得不使用一百萬個反引號來使它們工作。通過更改標籤來添加空格。 – alistaire

回答

0

它正在檢測對象'Name1',但由於您使用的是as.name,它正在讀取Name1的內容 - '示例Whitespace',然後將其解析爲對象。

要使用帶有空格的對象,請在對象周圍使用「標記」。

您的代碼就相當於

geom_point(data=df1, mapping=aes_string(x="x", y="y", color=`Example Whitespace`)), 

但是示例空白是不是在你的環境中的物體,所以這應該會失敗呢?