我正在尝试修改 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 自动绘制一次。我想改变这一点。有什么办法可以做到吗?
最佳答案
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/