【问题标题】:Change axis breaks in ggplot using a function使用函数更改ggplot中的轴中断
【发布时间】:2019-07-08 21:16:02
【问题描述】:

我正在寻找一种在 x 轴上创建设置中断步骤的方法,类似于此处发布的问题:Change axis breaks without defining sequence - ggplot

我注意到该问题的答案仅适用,因为正在绘制的数据在全局环境中被命名为 x 和 y。 ggplot 似乎没有将 aes 调用中定义的变量“x”和“y”传递给 scales_x_continuous 函数。

即这行得通:

x <- 1:10
y <- 1:10

df <- data.frame(x, y)
f <- function(x) seq(min(x), max(x), by = 2)
ggplot(df, aes(x,y)) + geom_point() + scale_y_continuous(breaks = f)

但这会产生错误:“...object 'x' not found”

rm(x, y) #to remove the objects x and y defined earlier
df <- data.frame("xvar" = 1:10, "yvar" = 1:10)
f <- function(x) seq(min(x), max(x), by = 2)
ggplot(df, aes(x,y)) + geom_point() + scale_y_continuous(breaks = f)

有没有办法传递在 ggplot 调用的 aes 部分中定义的变量并使第二段代码工作?

【问题讨论】:

  • 我的错。 @joran 适合我的可重现示例,我再次查看了上面示例应该代表的实际问题。结果scale_x_continuous(breaks = f(x)) 是产生我上面提到的错误的原因。解决方案当然是breaks = f

标签: r ggplot2


【解决方案1】:

您可以将变量命名为任何名称,ggplot 将使用您正在更改的比例指定的值。见下文:

library(tidyverse)

set.seed(123)

dat <- tibble(x = rdunif(10, 5, 20), 
              y = 1:10)

func <- function(bob) seq(min(bob), max(bob), 2)

dat %>% 
    ggplot(aes(x,y)) + 
    geom_point() + 
    scale_y_continuous(breaks = func) + 
    scale_x_continuous(breaks = func)

reprex package (v0.3.0) 于 2019-07-08 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2020-10-27
    • 2012-07-21
    • 2019-04-03
    • 1970-01-01
    相关资源
    最近更新 更多