说我有此数据帧:ggplo2在R:geom_segment显示不同的线比geom_line
treatment <- c(rep("A",6),rep("B",6),rep("C",6),rep("D",6),rep("E",6),rep("F",6))
year <- as.numeric(c(1999:2004,1999:2004,2005:2010,2005:2010,2005:2010,2005:2010))
variable <- c(runif(6,4,5),runif(6,5,6),runif(6,3,4),runif(6,4,5),runif(6,5,6),runif(6,6,7))
se <- c(runif(6,0.2,0.5),runif(6,0.2,0.5),runif(6,0.2,0.5),runif(6,0.2,0.5),runif(6,0.2,0.5),runif(6,0.2,0.5))
id <- 1:36
df1 <- as.data.table(cbind(id,treatment,year,variable,se))
df1$year <- as.numeric(df1$year)
df1$variable <- as.numeric(df1$variable)
df1$se <- as.numeric(df1$se)
正如我在以前的问题(draw two lines with the same origin using ggplot2 in R)提到的,我想用GGPLOT2在一个特定的显示我的数据办法。
我设法做到使用下面的脚本:
y1 <- df1[df1$treatment=='A'&df1$year==2004,]$variable
y2 <- df1[df1$treatment=='B'&df1$year==2004,]$variable
y3 <- df1[df1$treatment=='C'&df1$year==2005,]$variable
y4 <- df1[df1$treatment=='D'&df1$year==2005,]$variable
y5 <- df1[df1$treatment=='E'&df1$year==2005,]$variable
y5 <- df1[df1$treatment=='E'&df1$year==2005,]$variable
y6 <- df1[df1$treatment=='F'&df1$year==2005,]$variable
p <- ggplot(df1,aes(x=year,y=variable,group=treatment,color=treatment))+
geom_line(aes(y = variable, group = treatment, linetype = treatment, color = treatment),size=1.5,lineend = "round") +
scale_linetype_manual(values=c('solid','solid','solid','dashed','solid','dashed')) +
geom_point(aes(colour=factor(treatment)),size=4)+
geom_errorbar(aes(ymin=variable-se,ymax=variable+se),width=0.2,size=1.5)+
guides(colour = guide_legend(override.aes = list(shape=NA,linetype = c("solid", "solid",'solid','dashed','solid','dashed'))))
p+labs(title="Title", x="years", y = "Variable 1")+
theme_classic() +
scale_x_continuous(breaks=c(1998:2010), labels=c(1998:2010),limits=c(1998.5,2010.5))+
geom_segment(aes(x=2004, y=y1, xend=2005, yend=y3),colour='blue1',size=1.5,linetype='solid')+
geom_segment(aes(x=2004, y=y1, xend=2005, yend=y4),colour='blue1',size=1.5,linetype='dashed')+
geom_segment(aes(x=2004, y=y2, xend=2005, yend=y5),colour='red3',size=1.5,linetype='solid')+
geom_segment(aes(x=2004, y=y2, xend=2005, yend=y6),colour='red3',size=1.5,linetype='dashed')+
scale_color_manual(values=c('blue1','red3','blue1','blue1','red3','red3'))+
theme(text = element_text(size=12))
正如你可以看到我同时使用geom_line和geom_segment以显示我的图线。
这几乎是完美的,但如果你仔细观察,要绘制的(2004年和2005年之间)的部分不显示在同一行的大小,尽管我用的脚本相同的参数值(即size=1.5
和linetype='solid'
或dashed
)。
当然,我可以手动更改段的大小以获得相似的线条,但是当我这样做时,线段不如使用geom_line
的线条那样流畅。 另外,通过在aes()
参数中包含size
或linetype
参数,我会遇到同样的问题(不同的线条形状)。
你有什么想法是什么导致了这种差异,我怎么能得到完全相同的形状为我的段和线?
我觉得这些线条有相同的大小。这似乎是光栅化算法的一个问题。由于随机抽样得到的数据不同,这个问题似乎发生在2006年至2007年,其中只使用了'geom_line'。 – Marcelo
事实上,当我删除'geom_segment'部分中的'颜色'参数时,颜色发生了变化...... 但是我不明白你对2006年到2007年的评论。数据框的构建方式,应该应用geom_line范围从1999年到2004年和/或从2005年到2010年,对吗? –
也许一个解决方案会添加一个带有'override.aes'类似参数的线段,就像图例一样?如果这样做有道理...... –