2016-09-07 75 views
0

我想在單個ggplot2圖表中使用多個geom_smooth圖層。當我嘗試這樣做時,配色方案就搞砸了。這是一個演示發生了什麼的例子。我們如何在單個圖表中使用多個geom_smooth?

我們構建一個簡單的數據框,我們想要可視化。

df = data.frame(x = c("a", "b", "c"), 
      y1 = seq(1, 3), 
      y1_upr = seq(2, 4), 
      y1_lwr = seq(0, 2), 
      y2 = seq(2, 4), 
      y2_upr = seq(2.5, 4.5), 
      y2_lwr = seq(1.5, 3.5)) 

我們可以很容易地看到y1和y2。

plot_obj = ggplot(data = df, aes(x = x, group = 1)) + 
    geom_line(aes(y = y1, colour = "y1")) + 
    geom_line(aes(y = y2, colour = "y2")) +  
    scale_colour_manual("", breaks = c("y1", "y2"), values = c("blue", "red")) 
plot_obj 

enter image description here 如果再加上一個geom_smooth,其行爲仍符合市場預期。

plot_obj + 
    geom_smooth(aes(y = y1, ymin = y1_lwr, ymax = y1_upr), stat="identity", fill="blue", alpha=0.2) 

enter image description here 最後,我們添加第二個geom_smooth層。

plot_obj + 
    geom_smooth(aes(y = y1, ymin = y1_lwr, ymax = y1_upr), stat="identity", fill="blue", alpha=0.2) + 
    geom_smooth(aes(y = y2, ymin = y2_lwr, ymax = y2_upr), stat="identity", fill="red", alpha=0.2) 

enter image description here

注意,頂行不再是紅色的最後一個圖表英寸爲什麼會發生這種情況,以及如何解決這個問題?謝謝!

+1

重塑你的數據,並添加分組變量 – user20650

+0

了'melt'答案給人的想法http://stackoverflow.com/questions/3777174/plotting-two-variables-as-lines-using-ggplot2-在同一張圖上 – user20650

+1

'geom_smooth'繪製藍線。所以如果你想像這樣添加單獨的圖層,你需要在'geom_smooth'圖層中使用'color =「red」''。如果您的某條線條不是藍色,您會在兩層中注意到它。 – aosmith

回答

1

當然,重塑你的數據集將讓事情變得更容易,並且是推薦的方法。但是,如果要繼續使用單獨的圖層:

因爲您還沒有爲geom_smooth映射color,所以它爲其繪製的平滑線使用藍色的默認顏色。如果您只需要功能區,請改用geom_ribbon

ggplot(data = df, aes(x = x, group = 1)) + 
    geom_line(aes(y = y1, colour = "y1")) + 
    geom_line(aes(y = y2, colour = "y2")) +  
    scale_colour_manual("", breaks = c("y1", "y2"), values = c("blue", "red")) + 
    geom_ribbon(aes(y = y1, ymin = y1_lwr, ymax = y1_upr), stat="identity", fill="blue", alpha=0.2) + 
    geom_ribbon(aes(y = y2, ymin = y2_lwr, ymax = y2_upr), stat="identity", fill="red", alpha=0.2) 

否則,你就需要爲每個平滑層內aes你的顏色映射或手動設置爲紅色,藍色或NA的aes之外。

ggplot(data = df, aes(x = x, group = 1)) + 
    geom_line(aes(y = y1, colour = "y1")) + 
    geom_line(aes(y = y2, colour = "y2")) +  
    scale_colour_manual("", breaks = c("y1", "y2"), values = c("blue", "red")) + 
    geom_smooth(aes(y = y1, ymin = y1_lwr, ymax = y1_upr, colour = "y1"), 
       stat="identity", fill="blue", alpha=0.2) + 
    geom_smooth(aes(y = y2, ymin = y2_lwr, ymax = y2_upr, colour = "y2"), 
       stat="identity", fill="red", alpha=0.2) 
1

我可能會做一些接近這個:

library(dplyr) 
df1 <- df %>% 
    select(x,contains("y1")) %>% 
    rename(y = y1,y_upr = y1_upr,y_lwr = y1_lwr) %>% 
    mutate(grp = "y1") 
df2 <- df %>% 
    select(x,contains("y2")) %>% 
    rename(y = y2,y_upr = y2_upr,y_lwr = y2_lwr) %>% 
    mutate(grp = "y2") 
df_all <- bind_rows(df1,df2) 

ggplot(df_all,aes(x = x,y = y,ymin = y_lwr,ymax = y_upr,group = grp)) + 
    geom_line(aes(color = grp)) + 
    geom_ribbon(aes(fill = grp),alpha = 0.2) 
相關問題