【问题标题】:How can I highlight subset of values in ggplot2 plots?如何突出显示 ggplot2 图中的值子集?
【发布时间】:2012-05-01 18:09:37
【问题描述】:

例如我有基本的堆积图:

ggplot(diamonds, aes(x=factor(color),fill=factor(cut)))+geom_bar(position="fill")

而且我有一小部分钻石的“克拉”值高于 3:

subset(diamonds,carat>3)

我想在图上突出显示这个特定的值(如果我们的钻石有 ID,比如点或标签),以查看它们位于分布的哪个部分。有没有可能做这样的事情?

PS:很遗憾,我不允许发布数据。

【问题讨论】:

    标签: r ggplot2 highlight subset


    【解决方案1】:

    以下将“克拉大于 3”的计数插入到条形段中。我已将问题分解为多个步骤。步骤 1:识别“克拉大于 3”的新变量。第 2 步:获取计数汇总表 - 每种颜色和切割的钻石数量,以及每种颜色和切割的“克拉大于 3”。我使用了 plyr 包中的 ddply() 函数。第 3 步:条形图没有标签的绘图。第 4 步:在汇总表中添加一个变量,给出标签的 y 位置。第 5 步:将 geom_text 图层添加到图中。geom_text 的数据框是汇总表。geom_text() 需要美学标签(在这种情况下,“克拉大于 3' 的计数”)、y 位置(在上一步中计算)和 x 位置(颜色)。

    library(ggplot2)
    library(plyr)
    
    # Step 1
    diamonds$caratGT3 = ifelse(diamonds$carat > 3, 1, 0)
    
    # Step 2
    diamonds2 = ddply(diamonds, .(color, cut), summarize, CountGT3 = sum(caratGT3))
    diamonds2$Count = count(diamonds, .(color, cut))[,3]
    diamonds2
    
    # Step 3
    p = ggplot() + geom_bar(data = diamonds, aes(x=factor(color),fill=factor(cut)))
    
    # Step 4
    diamonds2 <- ddply(diamonds2,.(color), 
            function(x) { 
              x$cfreq <- cumsum(x$Count) 
              x$pos <- (c(0,x$cfreq[-nrow(x)]) + x$cfreq) / 2 
              x 
            }) 
    
    # Step 5
    (p  <- p + geom_text(data = diamonds2, 
       aes(x = factor(color), y = pos, label = CountGT3),
       size = 3, colour = "black", face = "bold"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多