How to have dynamic point tunneling on R ggplot fa

2019-06-14 16:47发布

I would like to have a dynamic "point tunneling" i.e. the darker gray area drawing around the neighborhood of the points. I think the great answer of the thread ggplot legends - change labels, order and title is based on experimental values defined in dtt of the thread. Code which makes a rectangular darker gray area around the points in Fig. 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) 

Fig. 1 Output with discrete rectangular point tunneling, Fig. 2 Expected result example from the thread

enter image description here enter image description here

Expected output: dynamic point tunnelling i.e. drawing of darker gray area around the points like in Fig. 2 but spanning for each facet individually

R: 3.4.0 (backports)
OS: Debian 8.7

标签: r ggplot2
1条回答
Melony?
2楼-- · 2019-06-14 17:17

You can define the yrange for each facet and then use that in the plot:

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

Here's a function that allows you to specify the data frame, the x and y variables and the facetting/grouping variable.

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

If what you really wanted were confidence bands, then use 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

查看更多
登录 后发表回答