[英]R: connect points on a graph (ggplot2)
假設我有以下形式的數據:
library(ggplot2)
Data <- data.frame(
"ID" = c("ABC111", "ABC111", "ABC111", "ABC111", "ABC112", "ABC112", "ABC112", "ABC113", "ABC113", "ABC114", "ABC115"),
"color" = c("red", "red", "red", "red", "blue", "blue", "blue", "green", "green", "black", "yellow"),
"start_date" = c("2005/01/01", "2006/01/01", "2007/01/01", "2008/01/01", "2009/01/01", "2010/01/01", "2011/01/01", "2012/01/01", "2013/01/01", "2014/01/01", "2015/01/01"),
"end_date" = c("2005/09/01", "2006/06/01", "2007/04/01", "2008/05/07", "2009/06/01", "2010/10/01", "2011/12/12", "2013/05/01", "2013/06/08", "2015/01/01", "2016/08/09")
)
Data$ID = as.factor(Data$ID)
Data$color = as.factor(Data$color)
現在我想做的是每一行,plot start_date 和 end_date... 然后用直線連接它們。 我相信這可以通過 ggplot2 中的 geom_line() 來完成。
我嘗試使用以下代碼:
q <- qplot(start_date, end_date, data=Data)
q <- q + geom_line(aes(group = ID))
q
但是圖表看起來與我的預期完全不同。
誰能告訴我我做錯了什么?
謝謝
以下內容對您有用嗎?
ggplot(data = Data, aes(start_date, end_date, color = ID))+
geom_line(aes(group = ID))+
geom_point()
或者也許geom_segment
?
# Adding x and y coordinates for geom_segment
Data$x <- as.character(as.Date(Data$start_date) + (as.Date(Data$end_date) - as.Date(Data$start_date)))
Data$y <- 1:nrow(Data)
ggplot(data = Data, aes(x, y, colour = ID))+
geom_segment(aes(xend = start_date, yend = end_date))
這是使用tidyverse
package 的解決方案。 我使用原始數據中每一行的數量作為 plot 中的 y 軸值。 由於這些值沒有意義,我從 plot 中刪除了 y 軸標題、標簽和刻度。
library(tidyverse)
Data %>%
# Number each row in its order of appearance,
# save this numbers in a new column named order
rowid_to_column("order") %>%
# Change data from wide to long format
pivot_longer(cols = c(start_date, end_date),
names_to = "date_type",
values_to = "date") %>%
# Ggplot, use date as x, order as y, ID as col and order as group
ggplot(aes(x = date,
y = order,
col = ID,
group = order)) +
# Draw points
geom_point()+
# Draw lines
geom_line() +
# Maybe you want to remove the y axis title, text and ticks
theme(axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
# I added a vertical format to the x axis labels
# it might easier to read this way
axis.text.x = element_text(angle = 90, vjust = 0.5))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.