【问题标题】:How to display the median value in a boxplot in ggplot?如何在ggplot的箱线图中显示中值?
【发布时间】:2012-11-02 10:30:44
【问题描述】:

我正在尝试使用 ggplot() 在箱形图中显示中值(即水平条)。 R 不断要求指定 y 轴。我有点卡住了。

p <-structure(list(TYPE = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 3L, 3L, 3L, 3L, 2L, 
3L, 3L, 3L, 3L, 3L, 2L, 3L, 3L, 2L, 3L, 2L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 2L, 3L, 3L, 3L, 1L, 2L, 3L, 3L, 2L, 3L, 3L, 3L, 1L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L), .Label = c("PM BUSINESS", 
"PM CONSUMER", "PREPAY"), class = "factor"), TOTALREV = c(52.13, 
53.01, 396.49, 596.52, 0, 33.89, 183.43, 0, 174.67, 120.56, 619.29, 
171, 142.2, 77.14, 16.69, 176.86, 103.79, 799.8, 137.84, 187.84, 
201.05, 16.69, 154.95, 195.98, 17.07, 158.96, 166.86, 8.89, 434.59, 
34.55, 196.97, 783.74, 216.27, 1533.98, 137.6, 52.22, 88.61, 
69.52, 52.18, 368.22, 139.89, 214.22, 163.46, 295.49, 319.73, 
933.91, 199.19, 118.72, 0, 174.99, 141.72, 52.12, 115.25, 106.57, 
106.12, 153.84, 1.45, 4.32, 168.93, 34.76, 249.21, 101.25, 87.69, 
20.62, 0.87, 17.39, 0, 34.5, 131.36, 0, 106.43, 257.45, 0, 0, 
256.63, 466.93, 44.25, 339.15, 71.42, 270.81, 145.85, 670.52, 
187.06, 170.61, 153.59, 21.69, 166.14, 97, 104.4, 517.19, 230.78, 
14.11, 52.33, 398.61, 56.65, 0, 26.02, 0, 154.78, 154.78)), .Names = c("TYPE", 
"TOTALREV"), row.names = 23961:24060, class = "data.frame")

x6.3 <- qplot(TYPE, TOTALREV, data =p, geom = "boxplot")
x6.3+ stat_bin(geom="text",aes(x=TYPE,y=TOTALREV,label=TOTALREV),size = 3, hjust = 0.5, vjust = -1.5,position ="identity")

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我不认为stat_bin 是要走的路:

    library(plyr)
    library(ggplot2)
    
    p_meds <- ddply(p, .(TYPE), summarise, med = median(TOTALREV))
    
    ggplot(p,aes(x = TYPE, y = TOTALREV)) + 
        geom_boxplot() + 
        geom_text(data = p_meds, aes(x = TYPE, y = med, label = med), 
                  size = 3, vjust = -1.5)
    

    附带说明一下,我通常发现人们一旦学会停止使用qplot,就不会对 ggplot 感到困惑。

    【讨论】:

    • + 1 表示远离qplot 的推荐。 (并击败我 30 秒)
    • 请注意,vjust 仅定义为从 0 到 1(请参阅 stackoverflow.com/questions/7263849/… 的最佳答案) - 尽管 vjust=-1.5 似乎在这里工作正常
    猜你喜欢
    • 1970-01-01
    • 2012-08-31
    • 2019-04-02
    • 2021-10-30
    • 2014-08-23
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    相关资源
    最近更新 更多