写在前面

ggplot的截断坐标轴一直以来做的不是很好,plot可以有一些比较复杂应用的函数可以解决截断坐标轴问题,但是ggplot出的大部分图表似乎无能为力。这里为大家介绍gg.gap包,用于ggplot截断坐标轴的绘制。

# install.packages("gg.gap")
library(gg.gap)
library(ggplot2)


data <-
  data.frame(x = c("Alpha", "Bravo", "Charlie", "Delta"),
             y = c(200, 20, 10, 15))
#画图
p1 = ggplot(data, aes(x = x, y = y, fill = x)) +
  geom_bar(stat = 'identity', position = position_dodge(),show.legend = FALSE) +
  theme_bw() +
  labs(x = NULL, y = NULL)

p1 = p1 +  theme_classic()
p2 = gg.gap(plot = p1,
           segments = c(25, 190),
           tick_width = 10,
           rel_heights = c(0.25, 0, 0.1),# 设置分隔为的三个部分的宽度
           ylim = c(0, 200)
           )

p2

gg lua点击坐标 gg修改抓坐标_数据可视化

data(mtcars)
library(ggplot2)
p<-ggplot(data = mtcars, aes(x = gear, fill = gear)) +
    geom_bar() +
    ggtitle("Number of Cars by Gear") +
    xlab("Gears")
p

gg lua点击坐标 gg修改抓坐标_gg lua点击坐标_02

#tick_width 默认不设置的时候就是一样的间隔
gg.gap(plot=p,
       segments=c(5,10),
       ylim=c(0,50))

gg lua点击坐标 gg修改抓坐标_ipa_03

#tick_width 设置两个阶段部分的不同坐标间隔
gg.gap(plot=p,
       segments=c(5,10),
       tick_width = c(1,10),
       ylim=c(0,50))

gg lua点击坐标 gg修改抓坐标_数据可视化_04

#segments list cantains more than one number vectors
gg.gap(plot=p,
       segments=list(c(2.5,4),c(5,10)),
       tick_width = c(1,0.5,10),
       ylim=c(0,50))

gg lua点击坐标 gg修改抓坐标_ipa_05

#rel_heights 设置每个间隔部分的相对高度
# list(c(2.5,4),c(5,10)) 多个间隔的指定方法
gg.gap(plot=p,
       segments=list(c(2.5,4),c(5,10)),
       tick_width = c(1,0.5,10),
       rel_heights=c(0.2,0,0.2,0,1),
       ylim=c(0,50))

gg lua点击坐标 gg修改抓坐标_微软_06

#reversed y-axis
p <- ggplot(data = mtcars, aes(x = gear, fill = gear)) +
    geom_bar() +
    ggtitle("Number of Cars by Gear") +
    xlab("Gears")+
    scale_y_continuous(trans = 'reverse')
p

gg lua点击坐标 gg修改抓坐标_编程语言_07

gg.gap(plot=p,
       segments=c(10,5),
       ylim=c(15,0))

gg lua点击坐标 gg修改抓坐标_微软_08

# 对于分面情况下的阶段坐标轴
library(ggplot2)
p<-ggplot(mtcars,aes(mpg,hp))+geom_point()
p1<-p+facet_wrap(~cyl,scales="free")
p1

gg lua点击坐标 gg修改抓坐标_数据可视化_09

gg.gap(plot = p1,ylim = c(60,200),segments = c(100,120))

gg lua点击坐标 gg修改抓坐标_ipa_10