如何在R中使用ggplot将两个数据帧的点彼此连接?

时间:2019-04-25 09:59:07

标签: r ggplot2

我有两个数据帧df1df2,如下所示:

> df1
  time value
1    1     6
2    2     2
3    3     3
4    4     1

> df2
  time value
1    2     3
2    3     8
3    4     4
4    5     5

我只想在一张数据图中绘制这些数据框,用彩色在其图上显示它们的名称,然后将df1的每个值连接到df2的相应值。其实,这是我想要的图表:

plot 1

我为尝试获得以上图表而编写的代码是:

ggplot() + 
  geom_point() +
  geom_line(data=df1, aes(x=time, y=value), color='green') + 
  geom_line(data=df2, aes(x=time, y=value), color='red') +
  xlab("time") +
  geom_text(aes(x = df1$time[1], y = 6.2, label = "df1", color = "green", size = 18)) +
  geom_text(aes(x = df2$time[1], y = 2.8, label = "df2", color = "red", size = 18)) +
  theme(axis.text=element_text(size = 14), axis.title=element_text(size = 14))

但是结果是:

plot 2

从图2中可以看到,即使我使用了geom_point()也没有点,名称颜色是错误的,df1的每个值与相应的{{ 1}},而且即使我在代码中确定了df2,也无法增加名称的文本大小。

2 个答案:

答案 0 :(得分:1)

zx8754’s answer非常相似的解决方案,但具有更明确的数据争用。从理论上讲,我的解决方案应该更通用,因为数据帧可以不排序,它们只需要一个公共变量即可加入。

library(magrittr)
library(ggplot2)

df1 = data.frame(
  time = 1:4,
  value = c(6,2,3,1),
  index = 1:4
)

df2 = data.frame(
  time = 2:5,
  value = c(3,8,4,5),
  index = 1:4
)


df3 = dplyr::inner_join(df1,df2,by = "index")

df1$type = "1"
df2$type = "2"

plot_df = dplyr::bind_rows(list(df1,df2))


plot_df %>% ggplot(aes(x = time, y = value, color = type)) +
  geom_point(color = "black")+
  geom_line() +
  geom_segment(inherit.aes = FALSE,
               data = df3,
               aes(x = time.x,
                   y = value.x,
                   xend = time.y,
                   yend = value.y),
               linetype = "dashed") +
  scale_color_manual(values = c("1" = "green",
                                "2" = "red"))

reprex package(v0.2.0)于2019-04-25创建。

答案 1 :(得分:0)

合并( cbind 数据帧,然后使用 geom_segment

ggplot() + 
  geom_line(data = df1, aes(x = time, y = value), color = 'green') + 
  geom_line(data = df2, aes(x = time, y = value), color = 'red') +
  geom_segment(data = setNames(cbind(df1, df2), c("x1", "y1", "x2", "y2")),
             aes(x = x1, y = y1, xend = x2, yend = y2), linetype = "dashed")

enter image description here