2017-05-24 22 views
-1

我想要一個動態的「點隧道」,即在點附近繪製較暗的灰色區域。 我認爲線程ggplot legends - change labels, order and title的偉大答案是基於線程的dtt中定義的實驗值。 代碼,這使得圖2中的點周圍的矩形暗灰色區域。1如何在R ggplot方面有動態點隧道?

molten <- structure(list(Vars = structure(c(1L, 2L, 1L, 2L, 1L, 2L), class = "factor", .Label = c("V1", "V2")), variable = structure(c(1L, 1L, 2L, 2L, 3L, 3L), class = "factor", .Label = c("REM", "Kevyt", "Syva")), value = c(160, 150, 380, 420, 110, 180)), .Names = c("Vars", "variable", "value"), row.names = c(NA, -6L), class = c("data.table", "data.frame")) 

library(ggplot2) 

# https://stackoverflow.com/a/12075912/54964 
ggplot(molten, aes(x = Vars, y = value, group = variable, colour = variable, ymin = 100, ymax = 450)) + 
    geom_ribbon(alpha=0.2, colour=NA)+ 
    geom_line() +  
    geom_point() +  
    facet_wrap(~variable) 

圖1個輸出具有離散矩形點隧穿, 圖從thread

enter image description here enter image description here 2預計結果例

預期輸出:動態點隧道,即在圖2中的點周圍繪製較深的灰色區域,但是單獨跨越每個方面

R:3.4.0(反向移植)
OS:Debian的8.7

+0

我不能從這個告訴你在找什麼,我認爲你必須更具體地說明正確的結果應該是什麼樣子。 – joran

+0

你的意思是你想要一個灰色的矩形,跨越'範圍(x)'和'範圍(y)'給定面內的點? – eipi10

回答

2

可以定義yrange爲每個小面,然後使用該在圖中:

library(tidyverse) 

ggplot(mtcars %>% group_by(cyl) %>% 
     mutate(miny=min(mpg), 
       maxy=max(mpg)), 
     aes(wt, mpg, group = cyl, 
      colour = factor(cyl), 
      ymin = miny, ymax = maxy)) + 
    geom_ribbon(alpha=0.2, colour=NA)+ 
    geom_line() +  
    geom_point() +  
    facet_wrap(~cyl) + 
    theme_bw() 

enter image description here

這裏有一個函數允許你指定數據框,x和y變量以及分面/分組變量。

my_plot = function(data, xx, yy, ff) { 

    yyr = range(data[,yy]) 

    ggplot(data, aes_string(xx, yy, ff)) + 
    geom_ribbon(aes(ymin = yyr[1], ymax = yyr[2]), alpha=0.2, colour=NA)+ 
    geom_line() +  
    geom_point() +  
    facet_grid(paste0("~ ", ff)) + 
    theme_bw() 
} 

my_plot(iris, "Petal.Width", "Sepal.Width", "Species") 

enter image description here

如果你真正想要的是置信帶,然後用geom_smooth

ggplot(iris, aes(Petal.Width, Sepal.Width, colour=Species, fill=Species)) + 
    geom_smooth(method="lm") + 
    geom_point(size=1) +  
    facet_grid(. ~ Species) + 
    theme_bw() 

enter image description here

+0

'geom_ribbon'是這裏的重要組成部分。 – shadowtalker

+0

'data.table'方法也很棒。 –

+0

你的意思是你想要矩形覆蓋所有面板中面板的全部y範圍? – eipi10