问题
I've done a faceted piechart with ggplot2 like this:
qplot(x=factor(1), data=mtcars, fill=factor(cyl)) +
geom_bar(width=1) +
coord_polar(theta="y") +
facet_grid(~gear)

but as all the piecharts share the y axis scale, some of them doesn't cover the full circle. I've tried with facet_grid(~gear, scales="free")
but it doesn't work.
How could I get full circles for all the piecharts?
回答1:
I think you just want position = 'fill'
:
ggplot(mtcars,aes(x = factor(1),fill=factor(cyl))) +
facet_wrap(~gear) +
geom_bar(width = 1,position = "fill") +
coord_polar(theta="y")
For future reference, from the Details section of geom_bar
:
By default, multiple x's occuring in the same place will be stacked a top one another by position_stack. If you want them to be dodged from side-to-side, see position_dodge. Finally, position_fill shows relative propotions at each x by stacking the bars and then stretching or squashing to the same height.
回答2:
If you are looking for another convenient way to do this, you can have a look at the ggstatsplot
package, both the bar and the pie charts.
# setup
set.seed(123)
library(ggstatsplot)
# pie chart
ggpiestats(mtcars, gear, cyl)
#> Warning in stats::chisq.test(x = data$main, y = data$condition, correct =
#> FALSE, : Chi-squared approximation may be incorrect

# bar chart
ggbarstats(mtcars, gear, cyl)
#> Warning in stats::chisq.test(x = data$main, y = data$condition, correct =
#> FALSE, : Chi-squared approximation may be incorrect

Created on 2019-06-23 by the reprex package (v0.3.0)
来源:https://stackoverflow.com/questions/18537378/faceted-piechart-with-ggplot2