当绘制具有共同x轴的多个线图时,如何分别给点着色?

时间:2019-03-30 10:59:02

标签: r ggplot2

我想制作3个重叠的线形图L,F和P,它们都具有相同的x轴深度,并且点由Depo着色。我发现了多种叠加图的方法,但是我正努力整合所需的颜色编码点。

以下是一些示例数据-很抱歉,由于某些原因它不会保持表格格式

depth     L     F     P Depo
67.48 1.003 1.063 1.066 Turb
67.63 1.004 1.020 1.024 Dri
67.73 1.011 1.017 1.028 Dri
67.83 1.006 1.007 1.014 Turb
67.92 1.003 1.029 1.032 Pro
68.06 1.004 1.007 1.011 Pro

我可以通过制作图表然后使用grid.draw将它们堆叠起来来得到想要的东西。但这会重复每个图的x轴值。

Lin <- ggplot(MyData, aes(x=depth, y=L)) + geom_line() + geom_point(data = MyData, aes(x=depth, y=L, color = Depo))    
Fab <- ggplot(MyData, aes(x=depth, y=P)) + geom_path() + geom_point(data = MyData, aes(x=depth, y=P, color = Depo))    
Fol <- ggplot(MyData, aes(x=depth, y=F)) + geom_path() + geom_point(data = MyData, aes(x=depth, y=F, color = Depo))    

grid.draw(rbind(ggplotGrob(Fol), ggplotGrob(Lin), ggplotGrob(Fab), size = "last"))

以下工作原理是在不重复x轴的情况下绘制图形,但我不知道如何通过Depo更改点。

mm <- melt(subset(MyData, select=c(depth, L, F,P)), id.var="depth")

ggplot(mm, aes(x = depth, y = value)) + geom_line(aes(color = variable)) +
  facet_grid(variable ~ ., scales = "free_y") + theme(legend.position = "none")

2 个答案:

答案 0 :(得分:0)

您可以取消上方图表的x轴:

Lin <- ggplot(MyData, aes(x=depth, y=L)) + geom_line() + geom_point(data = MyData, aes(x=depth, y=L, color = Depo)) + theme(axis.title.x=element_blank(),
                                                                                                                            axis.text.x=element_blank(),
                                                                                                                            axis.ticks.x=element_blank())   
Fab <- ggplot(MyData, aes(x=depth, y=P)) + geom_path() + geom_point(data = MyData, aes(x=depth, y=P, color = Depo)) 
Fol <- ggplot(MyData, aes(x=depth, y=F)) + geom_path() + geom_point(data = MyData, aes(x=depth, y=F, color = Depo)) + theme(axis.title.x=element_blank(),
                                                                                                                              axis.text.x=element_blank(),
                                                                                                                              axis.ticks.x=element_blank())

grid.draw(rbind(ggplotGrob(Fol), ggplotGrob(Lin), ggplotGrob(Fab), size = "last"))

答案 1 :(得分:0)

我建议不要使用melt。以我的经验,很难正确使用并且容易出错。我个人更喜欢tidyr动词gather()spread()

这是我处理图表的方法:

MyData %>%
  gather(variable, value, L:P) %>%
  ggplot() + aes(depth, value) +
  geom_path() + geom_point(aes(color = Depo, shape = Depo), size = 3) +
  facet_wrap(~variable, ncol = 1, scales = "free_y")

第一步是对L,F和P列进行gather操作,保持深度和Depo。我的图表代码与您尝试过的代码并没有很大差异。