使用geom_smooth时如何更改ggplot中以x轴因子为条件的线型?

时间:2019-01-16 19:32:21

标签: r ggplot2

假设我有一个LOESS回归图,其中x轴对应于一个分类变量:

library(ggplot2)

b <- structure(list(Expression = c(16.201081535896, 16.5138880401065, 
16.4244615700828, 1.62923743262849, 3.35379087562868, 6.99935683212696, 
4.81932543877313, 3.85300704208448, 7.32436891427261, 4.23627699164079, 
6.95731601433845, 4.33315521361287, 5.50596153247422, 13.0788494583573, 
13.6909487566244, 12.9520674350314), stage = structure(c(1L, 
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L), .Label = c("A", 
"B", "C", "D", "E"), class = "factor")), row.names = c(NA, 16L
), class = "data.frame")

ggplot(b, aes(as.numeric(stage), Expression)) +
  geom_point() +
  geom_smooth(span = 0.8) +
  scale_x_continuous(breaks = as.numeric(b$stage), labels = b$stage, minor_breaks = NULL)

link to plot 1

我想在LOESS回归的不同部分使用2种不同的线型。

具体来说,我想在A和B之间有一条虚线,在B和D之间有一条连续线,在D和E之间又有一条虚线。

因此,我遵循以下示例: conditional plot linetype in ggplot2

但是左侧和右侧的连接丢失了,只有黄土回归的中心部分保留了。

line.groups <- plyr::mapvalues(b$stage, 
                from = c("A", "B",  "C", "D", "E"),
                to = c(0, 1, 1, 1, 2))
ggplot(b, aes(as.numeric(stage), Expression)) +
  geom_point() +
  geom_smooth(aes(group=line.groups, linetype=line.groups), span = 0.8) +
  scale_linetype_manual(values=c(2,1,2)) +
  guides(linetype=FALSE) +  
  scale_x_continuous(breaks = as.numeric(b$stage), labels = b$stage, minor_breaks = NULL)

Link to image 2

是否有一种方法可以更改geom_smooth ggplot的线型,但要以x轴为条件(其中x是一个因子)?

编辑:

我尝试按照注释所建议的每个部分对geom_smooth使用三个单独的调用,但是每次调用之间的标准错误界限不会“平滑”。

ggplot(b, aes(as.numeric(stage), Expression)) +
  geom_point() +
  geom_smooth(data=b[b$stage %in% c("A", "B"),], linetype = "dashed", span = 0.8) +
  geom_smooth(data=b[b$stage %in% c("B", "C", "D"),], linetype = "solid", span = 0.8) +
  geom_smooth(data=b[b$stage %in% c("D", "E"),], linetype = "dashed",span = 0.8) +
  scale_linetype_manual(values=c(2,1,2)) +
  guides(linetype=FALSE) +  
  scale_x_continuous(breaks = as.numeric(b$stage), labels = b$stage, minor_breaks = NULL)

Link to sub-optimal solution

谢谢

1 个答案:

答案 0 :(得分:0)

为完整起见,我将在上面的评论中发布用户OTStats提供的解决方案:

ggplot(b, aes(as.numeric(stage), Expression)) +
  geom_point() +
  geom_smooth(data=b[b$stage %in% c("A", "B"),], linetype = "dashed", span = 0.8,se = FALSE) +
  geom_smooth(data=b[b$stage %in% c("B", "C", "D"),], linetype = "solid", span = 0.8, se = FALSE) +
  geom_smooth(data=b[b$stage %in% c("D", "E"),], linetype = "dashed",span = 0.8, se = FALSE) +
  geom_smooth(linetype = "blank",span = 0.4) +
  guides(linetype=FALSE) +  
  scale_x_continuous(breaks = as.numeric(b$stage), labels = b$stage, minor_breaks = NULL)

请注意,需要在geom_smooth的第四次调用中调整平滑级别,才能产生令人满意的结果,但是总的来说,此技巧解决了这个问题。

Link to solution