如何使用ggplot2在一行中添加多个线条样式?

时间:2013-05-28 17:21:58

标签: r graphics ggplot2

我正在尝试使用自己的数据集重新创建附加图形。附加的R脚本在那里是90%,但是我似乎找不到根据图形对线条进行样式化的方法。具体来说,我需要以固体开始的线条特征,以点结束并继续作为虚线。我更喜欢在R中使用ggplot2。

如何才能使我的数字中的每一行都稳固,直到x = 5然后以一个点结束,最后以虚线继续?

enter image description here

# Sample Dataset
Samples = c(1,2,3,4,5,6,7,8,9,10)
SestYB = c(2.1,3.89,5.42,6.73,7.87,8.86,9.75,10.56,11.3,12)
CILowYB = c(1.03,2.01,2.92,3.76,4.52,5.21,5.82,6.37,6.86,7.3)
CIUpYB = c(3.17,5.77,7.91,9.7,11.21,12.51,13.68,14.74,15.74,16.7)
SestEH = c(1.3,2.29,3.06,3.68,4.19,4.63,5.03,5.38,5.7,6)
CILowEH = c(0.34,0.73,1.13,1.5,1.84,2.13,2.39,2.61,2.79,2.95)
CIUpEH = c(2.26,3.85,4.98,5.85,6.54,7.14,7.66,8.15,8.61,9.05)
data.frame(Samples,SestYB,CILowYB,CIUpYB,SestEH,CILowEH,CIUpEH)

require(ggplot2)

mydata = data.frame(Samples,SestYB,CILowYB,CIUpYB,SestEH,CILowEH,CIUpEH)

# Variables
EH = mydata$SestEH
YB = mydata$SestYB

yb_lower = mydata$CILowYB
yb_upper = mydata$CIUpYB

eh_lower = mydata$CILowEH
eh_upper = mydata$CIUpEH

# Plot data
ggplot(mydata, aes(Samples)) + 
  xlab("Samples") +
  ylab("Species") +
  geom_line(aes(y=YB), 
            colour="blue", size = 1.25) + 
  geom_line(aes(y=EH), 
            colour="red", size = 1.25) +
  geom_ribbon(aes(ymin=yb_lower, ymax=yb_upper), 
              fill = "blue", 
              alpha=0.2) +
  geom_ribbon(aes(ymin=eh_lower, ymax=eh_upper), 
              fill = "red", 
              alpha=0.2) +
  theme(panel.background = element_blank()) +
  theme(panel.grid = element_blank()) +
  theme(axis.line = element_line(size = 1, colour = "dark gray", linetype = "solid"))

1 个答案:

答案 0 :(得分:5)

这是一个很长的解决方案。我使用了数据框mydata中的变量名称。

想法是分别绘制是绘制线段直到值5然后在值5之后。因此使用subset()函数。对于两个线段,包括值5以确保段连接。要添加点,请仅使用值5的geom_point()和子集数据。

ggplot() + 
  geom_line(data=subset(mydata,Samples<=5),aes(Samples,y=SestYB), 
            colour="blue", size = 1.25,linetype="solid") + 
  geom_line(data=subset(mydata,Samples>=5),aes(Samples,y=SestYB), 
            colour="blue", size = 1.25,linetype="dashed") +
  geom_line(data=subset(mydata,Samples<=5),aes(Samples,y=SestEH), 
          colour="red", size = 1.25,linetype="solid") + 
  geom_line(data=subset(mydata,Samples>=5),aes(Samples,y=SestEH), 
            colour="red", size = 1.25,linetype="dashed")+ 
  geom_ribbon(data=mydata,aes(Samples,ymin=CILowYB, ymax=CIUpYB), 
              fill = "blue", 
              alpha=0.2) +
  geom_ribbon(data=mydata,aes(Samples,ymin=CILowEH, ymax=CIUpEH), 
              fill = "red", 
              alpha=0.2)+
  geom_point(data=subset(mydata,Samples==5),aes(Samples,SestYB),size=5)+
  geom_point(data=subset(mydata,Samples==5),aes(Samples,SestEH),size=5)

enter image description here