Adding points from other dataset to ggplot2

前端 未结 2 959
自闭症患者
自闭症患者 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:15

    The issue is that you are assigning fill = factor(colorname)for the whole plot in your qplot call.

    So testplot2 will also try to map colorname to the fill aesthetic but there is no colorname column in the pointdata data.frame which is why you have this error message. If you rewrite it using ggplot, it looks like this :

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

    What you need to do is to apply the mapping only to the geom_bar call, like this :

    ggplot(bardata, aes(xname, yvalue)) +
      geom_bar(stat = "identity", aes(fill = factor(colorname)))+ 
      geom_point(data = pointdata, 
                 mapping = aes(x = xname, y = ypos, shape = factor(ptyname)))
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题