ggplot2 pie and donut chart on same plot

前端 未结 6 1776
花落未央
花落未央 2020-11-28 03:35

I am trying to replicate this \"enter with R ggplot. I have exactly the same data:

<         


        
6条回答
  •  执念已碎
    2020-11-28 04:02

    I find it easier to work in rectangular coordinates first, and when that is correct, then switch to polar coordinates. The x coordinate becomes radius in polar. So, in rectangular coordinates, the inside plot goes from zero to a number, like 3, and the outer band goes from 3 to 4.

    For example

    ggplot(browsers) + 
      geom_rect(aes(fill=version, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) +
      geom_rect(aes(fill=browser, ymax=ymax, ymin=ymin, xmax=3, xmin=0)) +
      xlim(c(0, 4)) + 
      theme(aspect.ratio=1) 
    

    enter image description here

    Then, when you switch to polar, you get something like what you are looking for.

    ggplot(browsers) + 
      geom_rect(aes(fill=version, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) +
      geom_rect(aes(fill=browser, ymax=ymax, ymin=ymin, xmax=3, xmin=0)) +
      xlim(c(0, 4)) + 
      theme(aspect.ratio=1) +
      coord_polar(theta="y")  
    

    enter image description here

    This is a start, but may need to fine tune the dependency on y (or angle) and also work out the labeling / legend / coloring... By using rect for both the inner and outer rings, that should simplify adjusting the coloring. Also, it can be useful to use the reshape2::melt function to reorganize the data so then legend comes out correct by using group (or color).

提交回复
热议问题