r - 使用分类数据创建线图而不连接线

标签 r ggplot2 na

尝试创建一个图表,其中 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

enter image description here

关于r - 使用分类数据创建线图而不连接线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60505478/

相关文章:

r - Sexpr 中的错误处理

r - ggplot2 : space axis ticks unevenly between equidistant values

R 变换数据框并移除 NA

r - 更改 R 的 kable 中的列宽不会更改标题的宽度

r - 如何将数据框的名称传递给 Excel 工作表(使用 xlsx 包)

r - 如何修复 R Shiny 中的 'Error: variable lengths differ (found for ' input$s')'

r - 在 ggplot 2 2.0 中向 facet labeller 添加表达式

r - 在ggplot中,使用像因子这样的数值变量来创建多个绘图,但使用数值来控制间距

r - 用先前值和后续值的平均值填充 NA 值

r - Dplyr产生NaN,而碱基R产生NA