【问题标题】:add minor breaks to ggplot without labels在没有标签的情况下向 ggplot 添加小中断
【发布时间】:2020-11-20 00:59:29
【问题描述】:

我想在使用ggplot() 生成的图形上添加次要 轴刻度和/或线条。这是一项看似简单的任务,但事实证明非常具有挑战性。我找到了this solution,但它相对不优雅,不适合我的应用程序。我将使用不同的数据多次重新绘制我的绘图,从而通过geom_vline() 更改轴限制并打破任何手动规范。

我阅读了scales::minor_breaks_width() 的文档并尝试将其用于scale_x_continuous()minor_breaks 参数,但它会引发有关“循环中断”的错误。

下面有一个reprex,有人可以提供建议吗?

library(tidyverse)

p <- mpg %>% 
  ggplot(aes(displ, hwy))+
  geom_point()

# major breaks are easy to set
p +
  scale_x_continuous(
    breaks = scales::breaks_width(width = 0.5, offset = 0))

# adding a minor breaks specification throws an error 
p +
  scale_x_continuous(
    breaks = scales::breaks_width(width = 0.5, offset = 0),
    minor_breaks = scales::minor_breaks_width(width = 0.01, offset = 0) )
#> Error in loop_breaks(range, breaks, f): argument "breaks" is missing, with no default

reprex package (v0.3.0) 于 2020 年 11 月 19 日创建

【问题讨论】:

标签: r ggplot2


【解决方案1】:

或者,您可能想尝试一种更简单的方法。 我使用了 0.1 的宽度,因为用 0.01 很难看到。

library(tidyverse)
p <- mpg %>% 
  ggplot(aes(displ, hwy))+
  geom_point()

brks = seq(1.5, 7, 0.1)
lbs <- ifelse(brks%%0.5 == 0, format(brks, digits = 1, nsmall = 1), "")
p +
  scale_x_continuous(
    breaks = brks, labels = lbs) 

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多