R:覆盖轨迹图和散点图

时间:2018-05-29 08:38:52

标签: r ggplot2 scatter-plot


我正在使用ggplot2和轨迹图,这些图就像散点图,但是由于特定的规则而连接点的线。
我的目标是使用散点图覆盖轨迹图,并且每个轨迹图都有不同的数据。 首先,数据:

# first dataset
ideal <- data.frame(ideal=c('a','b')
                ,x_i=c(0.3,0.8)
                ,y_i=c(0.11, 0.23))

# second dataset
calculated <- data.frame(calc = c("alpha","alpha","alpha")
                     ,time = c(1,2,3)
                     ,x_c = c(0.1,0.9,0.3)
                     ,y_c = c(0.01,0.26,0.17)
                     )

使用第一个创建散点图很简单:

library(ggplot2)
ggplot(calculated, aes(x=x_c, y=y_c)) + geom_point()

之后,我使用this helpful link创建了轨迹图:

library(grid)
library(data.table)

qplot(x_c, y_c, data = calculated, color = calc, group = calc)+ 
  geom_path (linetype=1, size=0.5, arrow=arrow(angle=15, type="closed"))+ 
  geom_point (data = calculated, colour = "red")+
  geom_point (shape=19, size=5, fill="black")

结果如下:

enter image description here

如何将ideal数据叠加到此轨迹图上(当然没有轨迹,它们应该只是点)?
提前谢谢!

1 个答案:

答案 0 :(得分:0)

通常不建议使用

qplot。以下是绘制两个数据帧的方法。但是,如果数据框已合并,ggplot可能会更适合您,并且您有一个xy列,其中包含method或{calculated列的ideal列1}}。

library(ggplot2)

ideal <- data.frame(ideal=c('a','b')
                    ,x_i=c(0.3,0.8)
                    ,y_i=c(0.11, 0.23)
                    )

# second dataset
calculated <- data.frame(calc = c("alpha","alpha","alpha")
                         ,time = c(1,2,3)
                         ,x_c = c(0.1,0.9,0.3)
                         ,y_c = c(0.01,0.26,0.17)
                         )

ggplot(aes(x_c, y_c, color = "calculated"), data = calculated) + 
  geom_point( size = 5) +
  geom_path (linetype=1, size=0.5, arrow = arrow(angle=15, type="closed"))+ 
  geom_point(aes(x_i, y_i, color = "ideal"), data = ideal, size = 5) + 
  labs(x = "x", y = "y", color = "method")

enter image description here