adding different curves to plots in R

谁说胖子不能爱 提交于 2020-05-28 06:44:17

问题


I know I can add the same curve to each plot pane as a layer using lattice and latticeExtra R packages (see blow).

But suppose we wanted to add different curves to each plot pane.

For example, in the below example, I wonder how to add v1 only to the top plot, v2 to the bottom-left plot, and v3 to the bottom-right plot?

library(lattice)
library(latticeExtra)    

set.seed(24)
v1 <- density(rnorm(1e3, 3.5))
v2 <- density(rnorm(1e3, 3))
v3 <- density(rnorm(1e3, 2.75))


foo <- xyplot((1:32*.01)~wt|gear , data = mtcars)
foo + layer(panel.polygon(v1, col = 2, alpha = 0.3))


回答1:


Here is one option

foo + 
   layer(if(panel.number() == 3) {
            panel.polygon(v1, col = 2, alpha = 0.3)
      } else if(panel.number() == 1) {
            panel.polygon(v2, col = 2, alpha = 0.3)
      } else{
           panel.polygon(v3, col = 2, alpha = 0.3)
    })

data

library(lattice)
library(latticeExtra)    

set.seed(24)
v1 <- density(rnorm(1e3, 3.5))
v2 <- density(rnorm(1e3, 3))
v3 <- density(rnorm(1e3, 2.75))


foo <- xyplot((1:32*.01)~wt|gear , data = mtcars)



回答2:


You can do it with ggplot2 and facet_grid:

library(ggplot2)
library(dplyr)

# user data
v1 <- (rnorm(1e3, 3.5))
v2 <- (rnorm(1e3, 3))
v3 <- (rnorm(1e3, 2.75))

# Make df1 from user data and associate with add gear value in `mtcars`
df1 <- data.frame(wt = c(v1, v2, v3),
                gear = as.factor(c(rep(3, 1000),
                        rep(4, 1000), 
                        rep(5, 1000))))

# select data from mtcars and add user defined values (`val`)
df2 <- mtcars %>% 
  mutate(val = 1:32 * 0.01) %>% 
  remove_rownames() %>% 
  mutate(gear = as.factor(gear)) %>% 
  select(c(val, gear, wt))


ggplot(df2, aes(x = wt, y = val,  #set up mapping with df2
                fill = gear)) + 
  geom_density(data = df1,  #make density plots of df1
      aes(x = wt, 
          fill = gear),
      inherit.aes = FALSE) + #next add points from df1
  geom_point(data = df2, aes(x = wt, y = val), inherit.aes = FALSE) +
  facet_grid(cols = vars(gear)) 


You can make the fill color more transparent by adding an alpha value to geom_density.



来源:https://stackoverflow.com/questions/61683136/adding-different-curves-to-plots-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!