【问题标题】:Modifying ggplot2 Y axis to use integers without enforcing an upper limit [duplicate]修改ggplot2 Y轴以使用整数而不强制上限[重复]
【发布时间】:2014-05-29 15:38:09
【问题描述】:

我正在尝试修改 ggplot2 中的轴,使其为一个小数点,并且每个整数都有一个标签。但是,我想这样做没有上限,以便它会自动调整到不同计数的数据。

我的问题与question posed here(我被标记为重复)之间的区别在于,我需要为许多不同的数据集自动进行这项工作,而不仅仅是针对单个数据集。它必须自动选择上限,而不是使用breaks=(0,2,4,...) 创建一个固定的 y 轴。下面的@DidzisElferts 已经很好地回答了这个问题。

这是我的工作:

library(data.table)
library(scales)
library(ggplot2)

mtcars <- data.table(mtcars)
mtcars$Cylinders <- as.factor(mtcars$cyl)
mtcars$Gears <- as.factor(mtcars$gear)
setkey(mtcars, Cylinders, Gears)
mtcars <- mtcars[CJ(unique(Cylinders), unique(Gears)), .N, allow.cartesian = TRUE]

ggplot(mtcars, aes(x=Cylinders, y = N, fill = Gears)) + 
               geom_bar(position="dodge", stat="identity") + 
               ylab("Count") + theme(legend.position="top") + 
               scale_x_discrete(drop = FALSE)

如您所见,ggplot2 使用小数点绘制坐标轴,并自动每隔 2.5 绘制一次。我想改变它。有什么办法吗?

【问题讨论】:

  • 我认为您不必为了做到这一点而从您绘制的每个数据集中推断特定的断点/最大值 y 值。
  • 这需要比我想要的更多的交互。我希望有一种方法可以做我需要做的事情,但它会自动设置上限,然后从那里添加轴线。
  • @joran 查看我的解决方案
  • @Jaap 您的解决方案完美地说明了我评论的正确性,即可能需要直接指定中断或计算每个数据集的最大值。
  • @joran 你是对的。当我再次阅读您的评论时,我明白了您的观点。我可能在第一次阅读后很快就得出了结论(这可能有点太快和肤浅了)

标签: r ggplot2 axis-labels


【解决方案1】:
integer_breaks <- function(x)
  seq(floor(min(x)), ceiling(max(x)))

ggplot(mtcars, aes(x=Cylinders, y = N, fill = Gears)) + 
  geom_bar(position="dodge", stat="identity") + 
  ylab("Count") + theme(legend.position="top") + 
  scale_y_continuous(breaks=integer_breaks) +
  scale_x_discrete(drop = FALSE)

【讨论】:

    【解决方案2】:

    使用scale_y_continuous(breaks=c(0,2,4,6,8,10))。所以你的绘图代码看起来像:

    ggplot(mtcars, aes(x=Cylinders, y = N, fill = Gears)) + 
      geom_bar(position="dodge", stat="identity") + 
      ylab("Count") + theme(legend.position="top") + 
      scale_y_continuous(breaks=c(0,2,4,6,8,10)) +
      scale_x_discrete(drop = FALSE)
    

    编辑:或者,您可以使用scale_y_continuous(breaks=seq(round(max(mtcars$N),0))) 自动将比例调整为 y 变量的最大值。当您希望彼此之间的休息时间超过 1 次时,您可以使用例如 seq(from=0,to=round(max(mtcars$N),0),by=2)

    【讨论】:

    • 我在scale_y_continuous 文档中看到了这一点。我希望找到另一种方式,我不必为每个图手动定义轴。
    • @black_sheep07 查看我的编辑
    • 我尝试使用scale_y_continuous(breaks=c(0,2,4,6,8,10,12))命令,发现ggplot2实际上仍然调整到合适的上限,即使你设置的y限制太高。
    • @black_sheep07 但当您将 y 限制设置为低时,它可能不会这样做;在那种情况下,我的第二种方法效果更好。我在今天早上制作的一个情节上对其进行了测试,并且在那个情节上它有效。
    • 是的。有没有办法把它四舍五入到下一个偶数?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2012-08-16
    • 1970-01-01
    • 2015-04-29
    • 2018-01-03
    • 2022-07-12
    相关资源
    最近更新 更多