简体   繁体   中英

How to connect points of two dataframes to each other using ggplot in R?

I have two dataframes df1 and df2 as follows:

> 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

I want to plot these dataframes in just one diagram, show their name on their plots with a colour, and connect each value of df1 to the corresponding value of df2 . Actually, here is the diagram which I want:

情节 1

The code which I wrote to try to get the above diagram is:

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))

But the result is:

情节 2

As you can see in plot 2, there are no points even I used geom_point() , the names colour are wrong, there is no connection between each values of df1 to the corresponding value of df2 , and also I cannot increase the text size for the names even I determined size = 18 in my code.

A very similar solution to zx8754's answer but with more explicit data wrangling. In theory my solution should be more general as the dataframes could be unsorted, they would just need a common variable to join.

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"))

Created on 2019-04-25 by the reprex package (v0.2.0).

Combine ( cbind ) dataframes then use 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")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM