How to graph with geom_ribbon

2019-08-03 18:34发布

问题:

I have three tables:

Upper  Bound  
    Q      C   
    1     30  
    2     50  
    3     40

Lower  Bound      
    Q      C       
    1     10   
    2     15     
    3     20 

Bad Data:

Q      C      Name  
1      50     Sample 1  
2      40     Sample 1  
3      30     Sample 1  
1      0      Sample 2  
2      60     Sample 2  
3      5      Sample 2

I want a graph that graphs the lower and upper bounds in gray and fills everything in between and graph the bad samples on top with different colors and a legend:

plot <- ggplot(Bad_Data, aes(x = Bad_Data$Q, y = Bad_Data$C, group = 1))
plot + geom_line(aes(color = N)) + geom_ribbon(aes(ymin = Lower_Bound$C, ymax = Upper_Bound$C))  

I tried that but it gave me this error:

Error: Aesthetics must be either length 1 or the same as the data (624): ymin, ymax, x, y, group

Anyone who can help me?

回答1:

Here is a start, you can tweak the colors and other parameters to get the dynamics exactly as you like. I have added a few aesthetics with description of what each does:

#Prepare
Bad_Data$Lower_Bound <- Lower_Bound$C
Bad_Data$Upper_Bound <- Upper_Bound$C

#Plot
library(ggplot2)
p <- ggplot(Bad_Data, aes(x = Q, y = C, color=Name, group=Name))
p <- p + geom_line()
p + geom_ribbon(aes(ymin=Lower_Bound, ymax=Upper_Bound), 
                alpha=0.1,       #transparency
                linetype=1,      #solid, dashed or other line types
                colour="grey70", #border line color
                size=1,          #border line size
                fill="green")    #fill color

Data

Here is the data:

Upper_Bound <- read.table(text="Q      C   
1     30  
                          2     50  
                          3     40", header=T)

Lower_Bound <- read.table(text="Q      C       
                          1     10   
                          2     15     
                          3     20", header=T) 

Bad_Data <- read.table(text="Q      C      Name  
                       1      50     Sample1  
                       2      40     Sample1  
                       3      30     Sample1  
                       1      0      Sample2  
                       2      60     Sample2  
                       3      5      Sample2", header=T)

Edit

Safer preparation:

Bad_Data$Lower_Bound <- Lower_Bound$C[match(Bad_Data$Q, Lower_Bound$Q)]
Bad_Data$Upper_Bound <- Upper_Bound$C[match(Bad_Data$Q, Upper_Bound$Q)]


标签: r ggplot2