如何在R ggpolot2图中向xaxis添加额外的离散点?

时间:2014-07-28 09:30:25

标签: r plot ggplot2 axis

我想在绘图中添加一些数据,其中xaxis是离散类型(按字母顺序排列)。我的数据有一些中断导致值没有出现在图中(某些x轴点根本没有出现)。

我想添加缺少xaxis值的这些。例如,我有这样的数据和情节:

df <-
  data.frame(x = rep(c("a", "b", "d", "e"), 2),
             group = c("A", "A", "A", "A", "B", "B", "B", "B"),
             value = rnorm(8))

library(ggplot2)
ggplot(df, aes(x, value, group = group, colour = group)) + 
geom_line()  

enter image description here

但我想添加&#34; c&#34;值到x轴并得到类似的东西:

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以使用%+%添加新数据。请参阅下面的示例:

# Your previous plot
p <- ggplot(df, aes(x, value, group = group, colour = group)) + 
  scale_x_discrete(limits = letters[1:5]) +
  geom_line()
# Adding new data (with value NA) and a point
p %+% rbind(df, data.frame(x="c", value=NA_real_, group=c("A", "B"))) +
  geom_point(data=data.frame(x="c", value=-1, group=NA)) 

答案 1 :(得分:1)

扩大@DavidArenburg的想法:

ggplot(df, aes(x, value, group = paste(group, x %in% c("a", "b")), colour = group)) + 
  geom_line()  +
  scale_x_discrete(limits = letters[1:5])