【发布时间】:2017-11-29 12:51:04
【问题描述】:
我用 R 和 ggplot2 做了一个饼图,差不多按照example #128 of the R Graph Gallery.
piePlot <- function(count, categories) {
dat <- data.frame(count = count, category = categories)
dat$fraction <- dat$count / sum(dat$count)
dat$ymax <- cumsum(dat$fraction)
dat$ymin <- c(0, head(dat$ymax, n = -1))
dat$label <- paste(dat$category, dat$count)
plot <-
ggplot(dat, aes(
fill = category,
ymax = ymax,
ymin = ymin,
xmin = 0,
xmax = 1
)) +
geom_rect() +
coord_polar(theta = "y") +
scale_fill_brewer(labels = dat$label, guide = "legend")
plot
}
piePlot(count = c(20, 10, 30),
categories = c("one", "two", "three"))
这是输出:
图例的颜色不匹配。根据传说,最大的应该是最黑暗的(三个30),显然不是这样。这是我的数据框在绘图之前的打印输出:
count category fraction ymax ymin label
1 20 one 0.3333333 0.3333333 0.0000000 one 20
2 10 two 0.1666667 0.5000000 0.3333333 two 10
3 30 three 0.5000000 1.0000000 0.5000000 three 30
这正是传说中的顺序,但 ggplot 在绘图时似乎以某种方式重新排序了字段。我就是不明白为什么。
我正在使用 R 版本 3.4.2 和 ggplot2 版本 2.2.1。
有谁知道这种重新排序是如何发生的以及为什么发生,以及我该如何抑制它?
【问题讨论】: