ggplot2将手动栏添加到现有的地块

时间:2018-04-18 20:07:58

标签: r ggplot2

我正在尝试将单个手动条添加到现有区域(功能区)图中。理想情况下,我只想指定条形的x(位置)和y(值)。

ExampleData <- data.frame(myID=c(1,2,3,4,5,6,7,8,9,10),PU=c(10,20,30,40,50,60,70,80,90,100))
MyPlot <- ggplot(ExampleData,aes(x=myID))
MyPlot <- MyPlot + geom_ribbon(aes(ymin=0, ymax=PU), fill="lightgray", color="darkgray", size=1)
MyPlot <- MyPlot + geom_col(aes(x=4,y=40), color="red", linetype="solid", size=1)
MyPlot

它几乎正常工作,但由于某种原因,40的值变为400,理想情况下我应该能够指定条的宽度(应该是我们在下面看到的一半)。

enter image description here

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

也许更喜欢这样的东西?

ExampleData <- data.frame(myID=c(1,2,3,4,5,6,7,8,9,10),
                          PU=c(10,20,30,40,50,60,70,80,90,100))
bar <- data.frame(xmin = 4,xmax= 4.5,ymin = 0,ymax = 40)
ggplot() + 
    geom_ribbon(data = ExampleData,
                aes(x = myID,ymin=0, ymax=PU), 
                fill="lightgray", 
                color="darkgray", size=1) + 
    geom_rect(data = bar,
              aes(xmin = xmin,xmax = xmax,ymin = ymin,ymax = ymax),
              color = "red")

当您在顶部ggplot()级别指定数据框然后尝试添加所有美学旨在“设置”而不是“映射”的图层时,您提到的40 vs 400问题就会发生。发生这种情况时最常见的情况是,当人们添加文本标签时,您最终会将每个文本标签的许多副本叠加在一起。

在这种情况下,ggplot会尝试在geom_col的上下文中解释您给出的{和1}}的x和y值,因此最终重复这些单值10次并堆叠结果条。