Adding points from other dataset to ggplot2

前端 未结 2 940
自闭症患者
自闭症患者 2021-02-19 21:26

There are already many questions about this theme, but I could not find one that answered my specific problem.

I have a barplot (see testplot1

2条回答
  •  不知归路
    2021-02-19 22:19

    Yeah, sometimes ggplot error descriptions are quite difficult to understand. First note: try to avoid qplot, for rather complicated plots it tends to obscure things. Your code is equivalent to

    ggplot(bardata, aes(xname, yvalue, fill = factor(colorname))) + 
      geom_bar(stat = "identity") + 
      geom_point(data = pointdata, aes(x = xname, y = ypos, shape = factor(ptyname))
    
    #Error in factor(colorname) : object 'colorname' not found
    

    And here's the problem: when you specify aes mapping within ggplot() (or qplot() in your case), this setting is automatically applied to any subsequent geom. You specified x, y and fill. For geom_bar, everything is okay. For geom_point you override x and y, but the fill is still mapped to colorname which doesn't exist in pointdata, therefore the error.

    If you mix several data frames, here's the recommended way to go: empty ggplot() plus specific aes for each geom.

    ggplot() + 
      geom_bar(data = bardata, aes(xname, yvalue, fill = factor(colorname)), stat = "identity") + 
      geom_point(data = pointdata, aes(xname, ypos, shape = factor(ptyname)))
    

    enter image description here

提交回复
热议问题