【问题标题】:Manually setting limits and ticks on x-axis after coord_flip() in ggplot2在 ggplot2 中的 coord_flip() 之后手动设置 x 轴上的限制和刻度
【发布时间】:2021-02-17 14:35:10
【问题描述】:

我正在尝试使用我自己的数据从 Healy 的 数据可视化(第 116 页,复制到下面)中重现一个情节。当我设法重现该图时,我想手动编辑 x 轴上的限制和刻度。编码变得混乱,因为我需要使用 coord_flip() 来绘制情节。

x 轴应该从 0 到 6,每 1 个单位有刻度。我现在已经尝试了十几个选项,但没有一个能满足我的需求。希望有人对如何解决这个问题提出意见。

这是我的代码:

p <- ggplot(data = df, mapping = aes(x = reorder(group,-yvar), y = yvar))

p <- p + geom_pointrange(mapping = aes(ymin = lbci,
                                         ymax = ubci)) +
  labs(x= "", y= "yvar_label") + coord_flip() +
  geom_hline(yintercept = 5, linetype="dotted", color = "red", size=1.5) +
  theme_bw() 
p

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您想要定义一个连续变量的轴,因此您应该为您的绘图使用scale_y_continuous() 函数,并定义您想要的中断。

    这是一个虚拟示例:

    library(ggplot2)
    data(iris)
    p <- ggplot(data = iris[c(1:3, 52:55, 102:105),], mapping = aes(x = reorder(Species,-Petal.Width), y = Petal.Width))
    
    p + geom_pointrange(mapping = aes(ymin = 0, ymax = 3)) +
      labs(x= "", y= "yvar_label") + coord_flip() +
      geom_hline(yintercept = 5, linetype="dotted", color = "red", size=1.5) + 
      scale_y_continuous(breaks = seq(from = 0, to = 3, by = 0.5), limits = c(0,3)) + 
      theme_bw() 
    

    编辑:对于绘图限制,您应该将 limits 参数提供给 scale_x/y_continuous() 函数。

    【讨论】:

    • 谢谢!我试过:scale_y_continuous(breaks = seq(from = 0, to = 6, by = 1))。虽然这会在 x 轴上设置正确的限制,但刻度是默认的 2 个单位(即 0、2 等)。添加 ylim(0,6) 会返回错误:“'y' 的刻度已经存在。为 'y' 添加另一个刻度,它将替换现有的刻度。”,而 xlim() 也返回错误。
    • 啊,对不起,我错过了你必须在 scale_y_continuous() 函数中直接包含限制的事实,如果你使用它。我会更新我的答案
    猜你喜欢
    • 1970-01-01
    • 2019-09-06
    • 2016-02-05
    • 2017-07-13
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    相关资源
    最近更新 更多