【问题标题】:Widen geom_rect()-rectangle in ggplot2 on discrete scale在离散尺度上加宽 ggplot2 中的 geom_rect()-rectangle
【发布时间】:2022-01-17 17:15:08
【问题描述】:

我有以下代码:

library(tidyverse)

exp<-data.frame(a=c(10,30,80,100),b=c("A","B","C","D"))

exp %>%
  ggplot(aes(b,a))+
  geom_rect(aes(xmin="A",xmax="D",ymin=0,ymax=50,fill="red")) +
  geom_point()

如您所见,“A”和“D”的值位于 geom_rect() 提供的矩形的边界上。如何让 geom_rect() 从 x=0 开始并使用绘图的整个宽度?我想在我的数据集中使用误差线,它们在矩形之外的一半。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    只需将xmin 和xmax 分别设置为-Inf 和Inf。

    exp %>%
      ggplot(aes(b,a)) +
      geom_rect(aes(xmin=-Inf,xmax=Inf,ymin=0,ymax=50,fill="red"))+
      geom_point()
    

    【讨论】:

      【解决方案2】:

      我必须修改您的 exp$a 才能从 0 开始

        exp<-data.frame(a=c(0,30,80,100),b=c("A","B","C","D"))
          exp %>% ggplot(aes(b,a))+
            geom_rect(aes(xmin="A",xmax="D",ymin=0,ymax=100,fill="red"))+
            geom_point()+
             scale_x_discrete(labels=c("A", "B", "C", "D"), expand=c(0, 0)) + 
             scale_y_continuous(expand = c(0, 50))
      

      【讨论】:

      • @Rfantic 感谢您完美的回答。我仍然将第一个答案标记为正确,因为它似乎更容易实现。
      • @user2386786 很好,但您也可以投票赞成答案。
      猜你喜欢
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多