简体   繁体   中英

adjust y-axis for missings in ggplot2?

First some toy data:

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)
  • When I want to visualize year by id for sex==1, I do

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

    How can I hide observation 2 from the graph so that the distance between each remaining id's is the same? Is there a general way how to adjust the distance between two ticks on the y-axis when my breaks are id?

  • Does the solution also works when using facets?

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

Edited based on OP's clarification

Create individual plots and use the gridExtra package.

I am not sure if this is what you are looking for, but the use of reorder() should help. Just to test it out, I changed the "id" value of 4 to be 7 in your toy dataframe.

To drop levels in individual plots, you can create 2 plots and then place them side by side.

    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))

If you notice, the id's without data are dropped. For example the following doesn't have id=2. 在此处输入图片说明

Now, you can use the gridExtra package which is meant for this purpose, to print out both the plots p1 and p2.

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

在此处输入图片说明

facet_grid() includes all levels by design

Using facet_grid directly won't work, but this is by design. Facet_grip has the drop=TRUE by default. Notice that you are not seeing id's=5 or 6. If an id appears in any one panel, it is included in all the other panels to facilitate comparison.

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM