說我有此數據幀: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'類似參數的線段,就像圖例一樣?如果這樣做有道理...... –