【问题标题】:Pie Chart: Plot and Legend Mismatch饼图:情节和图例不匹配
【发布时间】: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。

有谁知道这种重新排序是如何发生的以及为什么发生,以及我该如何抑制它?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    出现不匹配是因为 ggplot() 首先按字母顺序排列图例,即如果您不调用 scale_fill_brewer,图例条目将从上到下显示为“一个 20、三个 30、两个 10”但是您将图例的条目覆盖为“一个 20、两个 30、三个 10”。解决此问题的一种方法是将dat$label 定义为级别为 c("one 20", "two 10", "three 30") 的因子,因此图例按因子级别排序。

    长话短说,下面的代码应该可以解决您的问题:

    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 <- factor(paste(dat$category, dat$count), levels = paste(dat$category, dat$count))
    plot <-
    ggplot(dat, aes(
      fill = label, # fill by label not category
      ymax = ymax,
      ymin = ymin,
      xmin = 0,
      xmax = 1
    )) +
    geom_rect() +
    coord_polar(theta = "y") +
    scale_fill_brewer(guide = "legend") # no need for labels anymore
    plot
    }
    
    library(ggplot2)
    piePlot(count = c(20, 10, 30),
        categories = c("one", "two", "three"))
    

    【讨论】:

    • 太棒了!我已经有点怀疑了,因为每个人都在为这些情节使用因子。现在我知道为什么了:-)
    猜你喜欢
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 2021-10-31
    • 2015-08-19
    • 2020-01-21
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多