[英]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.