R 调整ggplot2中缺失的y轴?

R 调整ggplot2中缺失的y轴?,r,ggplot2,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

首先是一些玩具数据:

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轴上两个记号之间的距离

当使用facet时,解决方案是否也有效

p <- ggplot(df, aes(y=id))
p <- p + geom_point(aes(x=year))
p <- p + facet_grid(sex ~.)
根据OP的澄清进行编辑

创建单独的绘图并使用gridExtra包

我不确定这是否是您正在寻找的,但使用重新排序应该会有所帮助。 为了测试它,我将玩具数据框中的id值4改为7

要在单个绘图中放置标高,可以创建两个绘图,然后并排放置

    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))
分面网格包括设计的所有级别 直接使用facet_网格是行不通的,但这是经过设计的。默认情况下,Facet_夹点的drop=TRUE。请注意,您没有看到id=5或6。如果某个id出现在任何一个面板中,则该id将包含在所有其他面板中以便于比较

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

这是相当不清楚的。第一个图形只有四个点。如果你移走其中两个,它们之间的距离怎么可能不一样呢?哦,那是真的。很抱歉为了更准确,我修改了我的问题。谢谢。让我重新表述一下我的问题:从这个图中,我想消除id=3表示sex=0,id=2表示sex=1,因为没有oberservationsfacet_网格保留id,如果它们出现在任何一个片段中。您可以通过创建自己的切片图来解决这个问题,然后使用gridExtra进行布局。编辑我的答案以反映这一点。太好了,非常感谢!
p <- ggplot(df, aes(y=reorder(id, id)))
p <- p + geom_point(aes(x=year))
p <- p + facet_grid(sex ~.)
p