【问题标题】:Place annotation at the top of a series of histograms in ggplot2 using a for loop使用 for 循环将注释放在 ggplot2 中一系列直方图的顶部
【发布时间】:2012-06-16 16:40:37
【问题描述】:

我正在创建许多直方图,我想在图表顶部添加注释。我正在使用 for 循环绘制这些图,因此我需要一种方法将注释放在顶部,即使我的 ylims 从一个图更改为另一个图。如果我可以将每个图形的 ylim 存储在循环中,我可以使注释的 y 坐标根据当前图形而变化。我在注释中包含的 y 值必须随着循环在迭代中的进行而动态变化。这是一些示例代码来演示我的问题(注意注释是如何移动的。我需要根据每个图的 ylim 来更改它):

library(ggplot2)

cuts <- levels(as.factor(diamonds$cut))

pdf(file = "Annotation Example.pdf", width = 11, height = 8,
    family = "Helvetica", bg = "white")

for (i in 1:length(cuts)) {
  by.cut<-subset(diamonds, diamonds$cut == cuts[[i]])
  print(ggplot(by.cut, aes(price)) +
    geom_histogram(fill = "steelblue", alpha = .55) +
  annotate ("text", label = "My annotation goes at the top", x = 10000 ,hjust = 0, y = 220, color = "darkred"))
}    
dev.off()

【问题讨论】:

    标签: r for-loop ggplot2


    【解决方案1】:

    ggplot 在其位置使用Inf 来表示绘图范围的极值,而不更改绘图范围。所以可以将注解的y值设置为Inf,也可以调整vjust参数以获得更好的对齐效果。

    ...
    print(ggplot(by.cut, aes(price)) +
          geom_histogram(fill = "steelblue", alpha = .55) +
          annotate("text", label = "My annotation goes at the top", 
                   x = 10000, hjust = 0, y = Inf, vjust = 2, color = "darkred"))
    ...
    

    对于i&lt;-2,这看起来像:

    【讨论】:

      【解决方案2】:

      可能有更简洁的方法,但您可以获取最大计数并使用它在注释调用中设置 y

      for (i in 1:length(cuts)) {
      
        by.cut<-subset(diamonds, diamonds$cut == cuts[[i]])
      
        ## get the cut points that ggplot will use. defaults to 30 bins and thus 29 cuts
        by.cut$cuts <- cut(by.cut$price, seq(min(by.cut$price), max(by.cut$price), length.out=29))
      
        ## get the highest count of prices in a given cut.
        y.max <- max(tapply(by.cut$price, by.cut$cuts, length))
      
        print(ggplot(by.cut, aes(price)) +
          geom_histogram(fill = "steelblue", alpha = .55) +
          ## change y = 220 to y = y.max as defined above
          annotate ("text", label = "My annotation goes at the top", x = 10000 ,hjust = 0, y = y.max, color = "darkred"))
      }  
      

      【讨论】:

        猜你喜欢
        • 2014-02-26
        • 2014-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多