调整y轴在ggplot2中的缺失?

时间:2013-11-04 15:21:49

标签: r ggplot2

首先是一些玩具数据:

df = read.table(text = 
              "id      year    value sex  
1           2000    0   1
1           2001    1   0
1           2002    0   1
1           2003    0   0
2           2000    0   0
2           2002    0   0
2           2003    1   0
3           2002    0  1  
4           2000    0   0
4           2001    0   1
4           2002    1   0
4           2003    0   1 ", sep = "", header = TRUE)
  • 当我想通过id为性别== 1想象年份时,我做

    df2 <- df[df$sex==1,]
    p <- ggplot(df2, aes(y=id))
    p <- p + geom_point(aes(x=year))
    p
    

    如何从图表中隐藏观察2,以便每个剩余id之间的距离相同?当我的休息是id时,是否有一般的方法如何调整y轴上两个刻度之间的距离?

  • 使用构面时,解决方案是否也有效?

    p <- ggplot(df, aes(y=id))
    p <- p + geom_point(aes(x=year))
    p <- p + facet_grid(sex ~.)
    

1 个答案:

答案 0 :(得分:0)

根据OP的澄清

进行编辑

创建单个图并使用 gridExtra 包。

我不确定这是否是您要找的,但 reorder() 的使用应该会有所帮助。 为了测试它,我在玩具数据框中将“id”值4更改为7。

要删除单个图中的级别,您可以创建2个图,然后将它们并排放置。

    df2 <- df[df$sex==1,]
p1 <- ggplot(df2, aes(y=(reorder(id, id))))
p1 <- p1 + geom_point(aes(x=year))
p1


df3 <- df[df$sex==0,]
p2 <- ggplot(df3, aes(y=(reorder(id, id))))
p2 <- p2 + geom_point(aes(x=year))

如果您注意到,则删除没有数据的ID。例如,以下内容没有id = 2。 enter image description here

现在,您可以使用专门用于此目的的gridExtra包来打印出p1和p2图。

require(gridExtra)
grid.arrange(p1, p2, ncol=2)

enter image description here

facet_grid()按设计包含所有级别

直接使用facet_grid将无法正常工作,但这是设计使然。 Facet_grip默认为drop=TRUE。请注意,您没有看到id = 5或6.如果ID出现在任何一个面板中,它将包含在所有其他面板中以便于比较。

p <- ggplot(df, aes(y=reorder(id, id)))
p <- p + geom_point(aes(x=year))
p <- p + facet_grid(sex ~.)
p

enter image description here