尝试创建一个图表,其中 x 和 y 都是因子,但如果存在间隙,我不希望连接这些线。我怎样才能做到这一点?
library(ggplot2)
df <- data.frame(x = c('a', 'b', 'c', 'd', 'e'), y = c('a', 'a', NA, 'a', 'a'))
ggplot(df, aes(x = x, y = y, group = y)) +
geom_point() +
geom_line()
不要在情节中使用 NA,并且 b 和 d 之间不应该有一条线。
最佳答案
这可能需要对您的完整数据集进行额外的工作,但一种方法是创建一个分组变量以在 ggplot 中使用以防止不需要的连接。
df <- data.frame(x = c('a', 'b', 'c', 'd', 'e'), y = c('a', 'a', NA, 'a', 'a'), stringsAsFactors = FALSE)
df %>%
mutate(grp = with(rle(y), rep(seq_along(lengths), lengths))) %>% # y can't be a factor
mutate_all(as.factor) %>%
na.omit() %>% # Drop NA cases so they're not plotted
ggplot(aes(x = x, y = y, group = grp)) +
geom_point() +
geom_line() +
scale_x_discrete(drop = FALSE) # Preserve empty factor levels in the plot
关于r - 使用分类数据创建线图而不连接线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60505478/