修改ggplot2 Y轴以使用整数而不强制执行上限 [英] Modifying ggplot2 Y axis to use integers without enforcing an upper limit

查看:86
本文介绍了修改ggplot2 Y轴以使用整数而不强制执行上限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修改ggplot2中的轴,以便它是一个小数点,并为每个整数都有一个标签.但是,我想没有上限,以便它可以自动调整为不同计数的数据.

I am trying to modify the axes in ggplot2 so that it is one decimal point and has a label for every integer. However, I want to do it without an upper limit so that it will automatically adjust to data of different counts.

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

The difference between my question and the question posed here (that I was flagged as being a duplicate of) is that I need to make this work automatically for many different data sets, not just for a single one. It must automatically choose the upper limit instead of creating a fixed y-axis with breaks=(0,2,4,...). This question has been answered extremely well by @DidzisElferts below.

这是我的作品:

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进行自动绘制.我想改变一下.有办法吗?

As you can see, ggplot2 is plotting the axes with a decimal point and doing it every 2.5 automatically. I'd like to change that. Any way to do so?

推荐答案

使用scale_y_continuous(breaks=c(0,2,4,6,8,10)).这样您的绘图代码将如下所示:

Use scale_y_continuous(breaks=c(0,2,4,6,8,10)). So your plotting code will look like:

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)


Alternatively you can use scale_y_continuous(breaks=seq(round(max(mtcars$N),0))) in order to automatically adjust the scale to the maximum value of the y-variable. When you want the breaks more then 1 from each other, you can use for example seq(from=0,to=round(max(mtcars$N),0),by=2)

这篇关于修改ggplot2 Y轴以使用整数而不强制执行上限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆