如何在R ggplot方面进行动态点隧道?

时间:2017-05-24 20:01:01

标签: r ggplot2

我想有一个动态的点隧道"即在点附近绘制的较暗的灰色区域。 我认为线程ggplot legends - change labels, order and title的好答案是基于线程dtt中定义的实验值。 在图1中的点周围形成矩形深灰色区域的代码

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带有离散矩形点隧道的输出, 图2 thread

的预期结果示例

enter image description here enter image description here

预期输出:动态点隧道效应,即在图2中的点周围绘制较暗的灰色区域,但是单独跨越各个方面

R:3.4.0(backports)
操作系统:Debian 8.7

1 个答案:

答案 0 :(得分: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变量以及facetting / grouping变量的函数。

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