【问题标题】:How to tweak the extent to which an axis is drawn in ggplot2? [duplicate]如何调整在ggplot2中绘制轴的程度? [复制]
【发布时间】:2014-08-15 13:54:06
【问题描述】:

我对 ggplot2 比较陌生,多年来一直在 R 中使用基本图形。我一直喜欢基本图形的一件事是轴中的额外填充,这样两个轴就不会在原点接触。下面是基础图形中的一个简单示例:

png(file="base.png")
plot(x,y, bty="n")
dev.off()

这使得:

然而,当我在 ggplot2 中做类似的事情时

require(ggplot2)
x <- y <- 1:10
png(file="qplot.png")
qplot(x, y) + theme_classic()
dev.off()

我明白了:

如何调整轴的绘制范围?例如对于 y 轴,我希望它停止在 10.0,而不是继续到 10.5 左右?

更新:感谢 cmets。我现在有我想要的;这是一个 sn-p,它仅将轴绘制到每个轴上的最小/最大刻度。

o = qplot(x, y) + theme_classic() +
  theme(axis.line=element_blank())
oo = ggplot_build(o)
xrange = range(oo$panel$ranges[[1]]$x.major_source)
yrange = range(oo$panel$ranges[[1]]$y.major_source)
o = o + geom_segment(aes(x=xrange[1], xend=xrange[2], y=-Inf, yend=-Inf)) +
  geom_segment(aes(y=yrange[1], yend=yrange[2], x=-Inf, xend=-Inf))
plot(o)

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    使用函数scale_x_continuous()scale_y_continuous() 的参数expand=,您可以获得以特定值开始和结束的轴。但是,如果您不提供这些值,那么它将看起来像是被削减了。

    qplot(x, y) + theme_classic()+
          scale_x_continuous(expand=c(0,0))
    

    要获得基本图的外观,一种解决方法是使用 theme() 删除轴线,然后使用 geom_segment() 添加从值 2 到 10(例如)的线而不是它们。

    qplot(x, y) + theme_classic()+
          scale_x_continuous(breaks=seq(2,10,2))+
          scale_y_continuous(breaks=seq(2,10,2))+
          geom_segment(aes(x=2,xend=10,y=-Inf,yend=-Inf))+
          geom_segment(aes(y=2,yend=10,x=-Inf,xend=-Inf))+
          theme(axis.line=element_blank())
    

    【讨论】:

      【解决方案2】:

      您可以通过影响 y 轴的缩放方式来调整此行为。 ggplot2 通常会根据数据选择范围并稍微扩展轴。

      以下示例将扩展设置为零并使用自定义限制来更好地控制轴。然而,正如您所看到的,让轴以最大值结束并不总是有益的,因为点字符可能会被截断。所以建议多留一点空间..

      require(ggplot2)
      x <- y <- 1:10
      qplot(x, y) + theme_classic() +
        scale_y_continuous(limits=c(-0.5,10), expand=c(0,0))
      

      【讨论】:

        猜你喜欢
        • 2022-11-18
        • 2022-08-16
        • 2020-06-06
        • 2015-01-04
        • 1970-01-01
        • 2017-03-01
        • 2015-10-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多