【问题标题】:dynamic scale_y_continuous for dynamic axis动态轴的动态 scale_y_continuous
【发布时间】:2020-08-18 05:12:33
【问题描述】:

扫描了我在 scale_y_continuous 上可以找到的所有内容,是否有办法实现以下目标:

调查数据的动态 y 轴,其中百分比和平均结果的限制发生变化。 P 是一个百分比值,轴需要设置为 0 - 100 M 为平均值,需设置为 1 - 6

如果所有值都在同一个图中,这将非常容易;但是我在 ggarrange 中有两个图表,第二个图表的值小于第一个图表,并且条形图未对齐。

library(ggplot2)

df <- data.frame(dose=c("D0.5", "D1", "D2"),
                 P = c(42, 98, 77.5),
                 M = c(2,3.4,5.5)
                 )
ggplot(data=df, aes(x=dose, y=P)) +
  geom_bar(stat="identity")

有没有办法将 P 的 scale_y_continuous 设置为 c(0,100) 和 M c(0.6)。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    要根据用户输入选择获得一个绘图,我们可以这样做:

    library(ggplot2)
    choice = 'P'
    
    if(choice == 'P') {
      p1 <- ggplot(data=df, aes(x=dose, y=P)) + geom_col() + 
                  scale_y_continuous(limits = c(0, 100))
    } else {
      p1 <- ggplot(data=df, aes(x=dose, y=M)) + geom_col() + 
              scale_y_continuous(limits = c(0, 6))
    }
    p1
    

    将两个图放在一起:

    您可以使用scale_y_continuous 为各个图设置limits,然后再将它们合并到ggarrange

    p1 <- ggplot(data=df, aes(x=dose, y=P)) + geom_col() + 
               scale_y_continuous(limits = c(0, 100))
    p2 <- ggplot(data=df, aes(x=dose, y=M)) + geom_col() + 
               scale_y_continuous(limits = c(0, 6))
    ggpubr::ggarrange(p1, p2)
    

    但是,您也可以考虑使用具有不同 y 轴的构面:

    df %>%
      tidyr::pivot_longer(cols = c(P, M)) %>%
      ggplot() + aes(dose, value) + geom_col()  +
      facet_wrap(.~name, scales = "free_y")
    

    【讨论】:

    • 非常感谢 Ronak,但轴将是 M 或 P,如果有意义的话,它们不会在同一个图中吗?所以会有一个下拉菜单来选择显示 M 或 P 但不能同时显示。
    • 哦..我明白了。但是,如果您在scale_y_continuous 中没有给出任何值,它不会自动选择 y 轴上的相关值吗?如果您仍想手动分配限制,您可以有条件地执行此操作。假设您在变量choice 中有用户选择,然后使用if/else 条件相应地设置限制。像 if(choice == 'P') scale_y_continuous(limits = c(0, 100))else scale_y_continuous(limits = c(0, 6)) 这样的东西。这行得通吗?
    • 是的,这会起作用,但我不知道如何让 if 语句起作用。像这样的工作: if(dataset$measure == 'P'), scale_y_continuous(limits = c(0, 100))
    • 非常感谢 Ronak,非常感谢。
    猜你喜欢
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多