简体   繁体   中英

How to reduce empty space in segmented plot in R?

I have the following data frame:

  person step start end
1    sam    A     0   4
2    sam    B     4   6
3   greg    A     2   7
4   greg    B     7  11

And I create the following plot:

library(ggplot2)
library(dplyr)
library(tidyr)

df

ggplot(df, aes(colour=step)) + 
  geom_segment(aes(x=start, xend=end, y=person, yend=person), size=3) +
  xlab("Duration")

At the very top and bottom there is a lot of empty space that I want to remove. How can I do this without changing the width/height ratio?

分段图减少空白空间

There seem to be at least two different ways to achieve this:

Using scale_y_discrete , as @WaltS suggested in a comment:

ggplot(df, aes(color = step))+
    geom_segment(aes(x=start, xend=end, y=person, yend=person), 
                 size = 3)+
    xlab("duration")+
    scale_y_discrete(expand = expand_scale(mult = 0.1))

The other one using coord_cartesian gives you some additional flexibility:

ggplot(df, aes(color = step))+
  geom_segment(aes(x=start, xend=end, y=person, yend=person), 
               size = 3)+
  xlab("duration")+
  coord_cartesian(expand = FALSE, #use no expansion
                  ylim = c(0.8,2.2), #set manually the limits in y
                  xlim = c(-1,12))  # set manually limits in x (or expand = F will make it tight!)

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