使用分类数据而不连接线来创建线图 [英] Create a line plot using categorical data and not connecting the lines
本文介绍了使用分类数据而不连接线来创建线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图创建一个图形,其中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
Trying to create a graph where both x and y are factors but I don't want the lines to be connected if there is a gap. How can I achieve this?
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()
Dont want the NA in the plot and there shouldn't be a line between b and d.
解决方案
This may need extra work with your full dataset but one approach is to create a grouping variable to use in ggplot to prevent connections that aren't wanted.
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
这篇关于使用分类数据而不连接线来创建线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文