代码之家  ›  专栏  ›  技术社区  ›  Matt Parker

更多的狗眼阴谋在R

  •  6
  • Matt Parker  · 技术社区  · 15 年前

    我用ggplot2制作了一些R中的牛眼图。它们看起来很令人愉快,每个人都很高兴——除了他们希望在图上绘制牛眼层的值。我很乐意把它们放在绘图的右下角,甚至是在绘图的空白处,但是我做这个有点困难。

    下面是示例数据:

    critters <- structure(list(Zoo = "Omaha", Animals = 50, Bears = 10, PolarBears = 3), .Names = c("Zoo", 
    "Animals", "Bears", "PolarBears"), row.names = c(NA, -1L), class = "data.frame")
    

    以及如何绘制:

    d <- data.frame(animal=factor(c(rep("Animals", critters$Animals),
           rep("Bears", critters$Bears), rep("PolarBears", critters$PolarBears)),
           levels = c("PolarBears", "Bears", "Animals"), ordered= TRUE))
    grr <- ggplot(d, aes(x = factor(1), fill = factor(animal))) +  geom_bar() +
      coord_polar() + labs(x = NULL, fill = NULL) +
      scale_fill_manual(values = c("firebrick2", "yellow2", "green3")) +
      opts(title = paste("Animals, Bears and Polar Bears:\nOmaha Zoo", sep=""))
    

    我想在这张图的右下角添加一个列表,

    Animals: 50
    Bears: 10
    PolarBears: 3
    

    但我不知道怎么做。到目前为止我的努力 annotate() 在一定程度上被极坐标所挫败。如果我必须在标题中加上数字,那就这样吧——但我总是希望有一个更优雅的解决方案。事先谢谢。

    编辑: 对于那些追随者来说,重要的一点是:靶心是一个映射到极坐标的条形图。条形图的ggplot2默认值是将它们合理地堆叠起来。然而,这意味着你的牛眼环也将被叠加(例如,在我的例子中,半径等于所有三个组的和63,而不是最大组的大小50)。我 不要 想一想,这是大多数人对牛眼阴谋的期望,尤其是当群体被嵌套的时候。使用 geom_bar(position = position_identity()) 将堆叠的环转换为分层的圆。

    编辑2:示例来自 ggplot2 文档:
    enter image description here

    2 回复  |  直到 12 年前
        1
  •  4
  •   Thierry    15 年前

    您可以将数字添加到图例中。

    library(ggplot2)
    critters <- structure(list(Zoo = "Omaha", Animals = 50, Bears = 10, PolarBears = 3), .Names = c("Zoo", "Animals", "Bears", "PolarBears"), row.names = c(NA, -1L), class = "data.frame")
    d <- data.frame(animal=factor(c(rep("Animals", critters$Animals),
           rep("Bears", critters$Bears), rep("PolarBears", critters$PolarBears)),
           levels = c("PolarBears", "Bears", "Animals"), ordered= TRUE))
    levels(d$animal) <- apply(data.frame(table(d$animal)), 1, paste, collapse = ": ")
    ggplot(d, aes(x = factor(1), fill = factor(animal))) +  geom_bar() +
      coord_polar() + labs(x = NULL, fill = NULL) +
      scale_fill_manual(values = c("firebrick2", "yellow2", "green3")) +
      opts(title = paste("Animals, Bears and Polar Bears:\nOmaha Zoo", sep=""))
    
        2
  •  5
  •   Ian Fellows    15 年前

    也可以直接将其添加到绘图中:

    grr <- ggplot(d, aes(x = factor(1), fill = factor(animal))) +  geom_bar() +
    coord_polar() + labs(x = NULL, fill = NULL) +
    scale_fill_manual(values = c("firebrick2", "yellow2", "green3")) +
    opts(title = paste("Animals, Bears and Polar Bears:\nOmaha Zoo", sep=""))+
    geom_text(y=c(3,10,50)-3,label=c("3","10","50"),size=4)
    grr