试图创建一个图形,其中 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
另一种方法是分解 y 并使用级别。用group = 1
分组。您可以用scale
重新标记。
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 = as.numeric(as.factor(y)), group = 1)) +
geom_point() +
geom_line() +
scale_y_continuous(breaks = 1, labels = 'a') +
labs(y = 'y')
#> Warning: Removed 1 rows containing missing values (geom_point).
创建于 2020-03-04 由reprex package(v0.3.0)
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(61条)