[英]How to adjust distances between years on x-axis and adjust line of geom_line(), in ggplot, R-studio?
我想使用ggplot的geom_line()創建折線圖,其中年份之間的所有距離都相等,與年份變量的實際值無關,並且如果之間只有兩年但不是之間,則連接geom_point()的點如果時間距離大於該距離。
例:
my.data<-data.frame(
year=c(2001,2003,2005,NA,NA,NA,NA,NA,NA,2019),
value=c(runif(10)))
至於情節,我嘗試了兩種不同的方法,但都不理想:
library(ggplot2)
library(dplyr)
my.data %>%
ggplot(aes(x=year,y=value)) +
geom_line() +
geom_point() +
scale_x_continuous(breaks=c(2001,2003,2005,2019), minor_breaks=F) +
theme_minimal()
my.data %>%
filter(!is.na(year)) %>%
ggplot(aes(x=factor(year),y=value)) +
geom_line() +
geom_point() +
theme_minimal()
這些問題有解決方案嗎? 我在俯視什么?
my.data %>%
ggplot(aes(x=year)) +
geom_line(aes(y = ifelse(year <= 2005,value,NA))) +
geom_point(aes(y = value)) +
scale_x_continuous(breaks=c(2001,2003,2005,2019), minor_breaks=F) +
theme_minimal()
也許像這樣的東西會工作
我遇到了一些令人費解的問題,但不是超級干凈的解決方案,但它可能會完成工作。 我正在檢查是否應該使用lead()將下一年連接到下一年。 並通過將它們變白來“刪除”適當的連接。 虛擬列將所有年份放在一行而不是兩年中。
my.data = data.frame(year=c(2001,2003,2005,2008,2009,2012,2015,2016,NA,2019),
value=c(runif(10))) %>%
filter(!is.na(year)) %>%
mutate(grouped = if_else(lead(year) - year <= 2, "yes", "no")) %>%
fill(grouped, .direction = "down") %>%
mutate(dummy = "all")
my.data %>%
ggplot(aes(x = factor(year),y = value)) +
geom_line(aes(y = value, group = dummy, color = grouped), show.legend = FALSE) +
geom_point() +
scale_color_manual(values = c("yes" = "black", "no" = "white")) +
theme_classic()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.