【r<-方案|转载】ggplot坐标轴截断

作者: 王诗翔 | 来源:发表于2019-02-17 11:50 被阅读29次

ggplot本身没有坐标轴截断的功能,所以一些文献中通过软件实现的截断图用ggplot难以实现,标准的方案是使用分面达到类似的效果。本文摘自Y叔《不一样的分面》


set.seed(2019-01-19)
d <- data.frame(
    x = 1:20, 
    y = c(rnorm(5) + 4, rnorm(5) + 20, rnorm(5) + 5, rnorm(5) + 22)
)

ggplot(d, aes(x, y)) + geom_col()
library(dplyr)

breaks = c(7, 17)
d$.type <- NA
d$.type[d$y < breaks[1]] = "small"
d$.type[d$y > breaks[2]] = "big"

d <- filter(d, .type == 'big') %>% 
    mutate(.type = "small", y = breaks[1]) %>% 
    bind_rows(d)

mymin = function(y) ifelse(y <= breaks[1], 0, breaks[2])               
p <- ggplot(d, aes(x, y)) + 
    geom_rect(aes(xmin = x - .4, xmax = x + .4, ymin = mymin(y), ymax = y)) +
    facet_grid(.type ~ ., scales = "free") + 
    theme(strip.text=element_blank())
p

相关文章

网友评论

    本文标题:【r<-方案|转载】ggplot坐标轴截断

    本文链接:https://www.haomeiwen.com/subject/vuhgeqtx.html