美文网首页ggplot2
ggplot2将坐标轴设置为整数值

ggplot2将坐标轴设置为整数值

作者: R语言数据分析指南 | 来源:发表于2021-01-09 23:53 被阅读0次

ggplot2将坐标轴设置为整数值的一个小例子,喜欢的小伙伴可以关注我的公众号R语言数据分析指南将分享更多实用文档,先行拜谢了

library(tidyverse)
A <- iris %>% 
  ggplot(aes(x = Petal.Width, y = Sepal.Width)) +
  geom_point(aes(color = Species),size=2) +
  scale_y_continuous(breaks = scales::pretty_breaks()) +
  theme_bw()
A
#scales::pretty_breaks
#> function (n = 5, ...) 
#> {
#>   force_all(n, ...)
#>   function(x) {
#>     breaks <- pretty(x, n, ...)
#>     names(breaks) <- attr(breaks, "labels")
#>     breaks
#>   }
#> }
#> <bytecode: 0x7ff8a81061d8>
#> <environment: namespace:scales>

修改pretty_breaks函数让其返回整数值

integer_breaks <- function(n = 5, ...) {
  fxn <- function(x) {
    breaks <- floor(pretty(x, n, ...))
    names(breaks) <- attr(breaks, "labels")
    breaks
  }
  return(fxn)
}
B <- iris %>% 
  ggplot(aes(x = Petal.Width, y = Sepal.Width)) +
  geom_point(aes(color = Species),size=2) +
  scale_y_continuous(breaks = integer_breaks()) +
  theme_bw()
library(patchwork)

A+B

相关文章

网友评论

    本文标题:ggplot2将坐标轴设置为整数值

    本文链接:https://www.haomeiwen.com/subject/xonhaktx.html