[英]Compare the two dataframes using line graph in r
quarter year value
q1 2012 100
q3 2013 200
q4 2014 400
q4 2015 250
q3 2014 400
數據框2
quarter year value
q1 2014 100
q3 2012 200
q4 2015 400
q4 2012 250
q3 2015 400
我想通過在r
作圖來比較這兩個。能否在這里提出建議?
注意:我嘗試了不同的方法,但是沒有運氣
plot(DF1$fy,DF1$value,
main ="Distribution of Assets in quarters across years",
xlab = 'years',ylab = 'vales',type='l')
您應該使用以下代碼獲得所需的輸出:
plot(DF1$year, DF1$value, type='l', col=1)
lines(DF2$year, DF2$value, col=2)
您可以使用dplyr::bind_rows
將兩個data.frames組合在一起,然后使用tidyr::expand
填充所有缺少的quarter
和year
。
現在,您可以使用ggplot
將line
和point
圖繪制在一起,如下所示:
library(tidyverse)
library(ggplot2)
bind_rows(df1, df2, .id="Name") %>%
right_join(expand(., Name, year = min(year):max(year),
quarter = c("q1","q2","q3","q4")), by=c("Name","quarter","year")) %>%
unite(YearQtr, c("year","quarter"), sep=":") %>%
ggplot(aes(x = YearQtr, y = value, group=Name, col = Name)) +
geom_point() +
geom_line()
結果:
數據:
df1 <- read.table(text="
quarter year value
q1 2012 100
q3 2013 200
q4 2014 400
q4 2015 250
q3 2014 400",
header = TRUE, stringsAsFactors = FALSE)
df2 <- read.table(text="
quarter year value
q1 2014 100
q3 2012 200
q4 2015 400
q4 2012 250
q3 2015 400",
header = TRUE, stringsAsFactors = FALSE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.