簡體   English   中英

如何使用R中的ggplot將兩個數據幀的點相互連接?

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

我有兩個數據幀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的相應值。 實際上,這是我想要的圖表:

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

但結果是:

情節 2

正如您在圖 2 中看到的,即使我使用geom_point()也沒有點,名稱顏色錯誤, df1每個值與df2的相應值之間沒有聯系,而且我也無法增加文本大小甚至我在代碼中確定的名稱size = 18

zx8754 的答案非常相似的解決方案,但具有更明確的數據處理。 從理論上講,我的解決方案應該更通用,因為數據幀可能未排序,它們只需要一個公共變量即可加入。

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 包(v0.2.0) 於 2019 年 4 月 25 日創建。

合並( 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")

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM