r - 修改 ggplot2 Y 轴以使用整数而不强制实现上限

标签 r ggplot2 axis-labels

我正在尝试修改 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)

Cylinder Graph

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

最佳答案

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)

关于r - 修改 ggplot2 Y 轴以使用整数而不强制实现上限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23937193/

相关文章:

r - 从另一个包导入 S3 泛型

r - 如何制作一个包含选项的列表,其中一个在正则表达式中是强制性的,R?

r - 如何按年份绘制 NetCDF 栅格图

r - 绘制年份的问题

Gnuplot - "zoom in"x 轴的一部分

r - fcase到多个输出

r - 移动 ggplot 图中的标签,使其与 x 轴刻度线匹配

r - ggplot2如何在单个面上叠加标记?

r - 在ggplot2中,如何限制geom_hline的范围?

matplotlib:向极坐标图刻度标签添加填充/偏移