Layered axes in ggplot?

前端 未结 2 448
旧时难觅i
旧时难觅i 2020-12-07 02:54

I\'m wondering if it\'s possible to make layered/segmented axes in GGLPOT2 (or another graphics package; I just prefer ggplot).

What I want to do is take the below

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 03:32

    Two steps to doing this:

    1. Add the group=animal aesthetic to the plot (tell it to group by animal)

    2. Add position="dodge" to your geom_bar layer (tell it the bars should be separate)

    Thus:

    ggplot(data, aes(x=period, y=value, fill=color, group=animal, color=animal)) +
            geom_bar(stat="identity", position="dodge")
    

    This looks like:

    enter image description here

    One of the issues here is that it doesn't describe which animal is which: there isn't a particularly easy way to fix that. That's why I would probably make this plot through faceting:

    ggplot(data, aes(x=animal, y=value, fill=color)) + geom_bar(stat="identity") +
        facet_wrap(~ period)
    

    enter image description here

提交回复
热议问题