2015-06-13 11 views
3

我想繪製一個線條圖,有多條線,根據分組變量進行着色。現在我想通過scale -command設置圖例標籤:動態創建ggplot圖例的表達式?

scale_color_manual(values = colors_values, labels = ...) 

的圖例標籤如下: 「×^ 2」, 「X^3」, 「X^4」 等,其中,所述範圍是動態創建的。我現在想動態創建表達式作爲標籤的文字,即

  • "x^2"應該成爲X
  • "x^3"應該成爲X

的圖例標籤的數量各不相同,所以我想到了類似as.expression(sprintf("x^%i", number))的東西,這當然不起作用label參數爲scale函數。

我搜索谷歌和堆棧溢出,但是,我還沒有找到一個工作解決方案,所以我希望有人可以幫助我在這裏。

這裏的一個可再現的例子:

poly.term <- runif(100, 1, 60) 
resp <- rnorm(100, 40, 5) 
poly.degree <- 2:4 
geom.colors <- scales::brewer_pal(palette = "Set1")(length(poly.degree)) 
plot.df <- data.frame() 
for (i in poly.degree) { 
    mydat <- na.omit(data.frame(x = poly.term, y = resp)) 
    fit <- lm(mydat$y ~ poly(mydat$x, i, raw = TRUE)) 
    plot.df <- rbind(plot.df, cbind(mydat, predict(fit), sprintf("x^%i", i))) 
} 
colnames(plot.df) <- c("x","y", "pred", "grp") 
ggplot(plot.df, aes(x, y, colour = grp)) + 
    stat_smooth(method = "loess", se = F) + 
    geom_line(aes(y = pred)) 
    scale_color_manual(values = geom.colors 
        # here I want to change legend labels 
        # lables = expresion??? 
        ) 

enter image description here

我想有圖例標籤爲x ,X 且x 。

+1

你能發佈一個可重現的例子。檢查http://stackoverflow.com/questions/19507742/using-expressionpaste-to-insert-math-notation-into-a-ggplot-legend – akrun

回答

2
ggplot(plot.df, aes(x, y, colour = grp)) + 
    stat_smooth(method = "loess", se = F) + 
    geom_line(aes(y = pred)) + 
    scale_color_manual(values = setNames(geom.colors, 
             paste0("x^",poly.degree)), 
        labels = setNames(lapply(poly.degree, function(i) bquote(x^.(i))), 
             paste0("x^",poly.degree))) 

如果更改比例中的值或標籤,確保正確的映射非常重要。因此,你應該總是使用命名向量。

resulting plot

+0

謝謝,工作正常! – Daniel