【问题标题】:Is there a way to set the x-axis to min and max value in ggplot?有没有办法在ggplot中将x轴设置为最小值和最大值?
【发布时间】:2021-07-23 05:51:30
【问题描述】:

数据:

Month<-c(jan,feb,mar,apr,may)
Values(10,5,8,12,4)

我想知道是否有一种方法可以将 x 轴设置为最小值和最大值,而无需对其进行硬编码。例如,除了硬编码 coord_cartesian(ylim = c(4, 12)) 之外,还有一种方法可以将 y 轴分配给 max 和 min,以便图形自动将限制设置为 4 和 12。

【问题讨论】:

    标签: r ggplot2 max axis min


    【解决方案1】:

    我们可以从“值”列中提取range

    library(ggplot2)
    ggplot(df1, aes(x = Month, y = Values)) + 
         geom_col() + 
         coord_cartesian(ylim = range(df1$Values))
    

    -输出


    如果我们需要更改刻度线,请使用scale_y_continuous

    rng_values <- range(df1$Values) -  c(2, 0)
    ggplot(df1, aes(x = Month, y = Values)) + 
         geom_col() + 
         coord_cartesian(ylim = rng_values ) + 
         scale_y_continuous(breaks = do.call(seq, 
            c(as.list(rng_values),
                list(by = 0.5))))
    

    数据

    df1 <- data.frame(Month = month.abb[1:5], Values = c(10, 5, 8, 12, 4))
    

    【讨论】:

    • 它有效,谢谢。只是想知道在做 range(df$Values) 时是否有办法控制粒度
    • @Gokul range 将最小值和最大值作为向量返回。您能在这里描述粒度的含义吗?如果你愿意,你也可以使用c(min(df$Values), max(df$Values))
    • 代替 4, 6, 8,10 有没有办法达到 4, 4.5, 5 5.5, 6, 6.5 等等,或者有没有办法在最小值以下开始某些值并达到某些值高于最大值,例如,图表从 2 变为 14,只是想知道它是否可能
    • 非常感谢您还有一件事是有一种方法可以在最小值以下开始某些值并在最大值以上设置某些值,例如图表从 2 到 14 只是想知道它是否可能或不是
    • @Gokul 您可以从范围中减去c(2, 0)。更新了帖子
    猜你喜欢
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多