簡體   English   中英

用正值和負值標記堆積條形圖

[英]Labelling stacked bar chart with positive and negative values

我正在使用 ggplot2 創建一個帶有負值的堆積條形圖,並嘗試將各部分的總和添加為每個條形頂部的標簽。 該代碼適用於沒有負值的條,但存在負值時的標簽保留在條內。

例子:

test = c("Test1", "Test1", "Test1", "Test2", "Test2", "Test2", "Test3", "Test3", "Test3")  
student = c("A", "B", "C", "A", "B", "C", "A", "B", "C")  
value = c(5,5,5,3,3,3,-2,6,7)

dummy = data.frame(test, student, value)

g = ggplot(data=dummy, aes(x=student, y=value, fill=test)) +   
      geom_bar(stat="identity") +   
      scale_fill_manual(values=c("brown4", "steelblue", "goldenrod3")) +
      geom_text(aes(label=value), size =3, position=position_stack(vjust=0.5), colour="white") +
      theme_classic() + 
      theme(text=element_text(family="serif", size=15, colour="black")) +   
      theme(axis.title=element_text(family="serif", size=15, colour="black")) +   
      theme(legend.title = element_blank()) +   
      theme(legend.position = c(0.2, 0.7)) +
      stat_summary(fun.y = sum, aes(label = ..y.., group = student), geom = "text", vjust = -1) +
      scale_y_continuous(limits = c(-4,20))

g

結果如下圖:

帶有堆積條形和負值的圖表 沒有負值的條的總和在條的頂部工作正常,但具有負值的條(學生 A)的總和位於紅色條的中間。

我怎樣才能解決這個問題?

您使用fun.y = sum作為匯總函數,它將組中的所有y值相加,包括負值。 這給出了標簽的正確總和,但位置不好。 對於位置計算,我們只想計算大於 0 的值的總和。

stat_summary讓我們指定最多 3 個函數, fun.yfun.yminfun.ymax 我們將修改fun.y位置,使其成為正值的總和,我們將添加fun.ymax作為常規sum並將其用於標簽:

g = ggplot(data=dummy, aes(x=student, y=value, fill=test)) +   
      geom_bar(stat="identity") +   
      scale_fill_manual(values=c("brown4", "steelblue", "goldenrod3")) +
      geom_text(aes(label=value), size =3, position=position_stack(vjust=0.5), colour="white") +
      theme_classic() + 
      theme(text=element_text(family="serif", size=15, colour="black")) +   
      theme(axis.title=element_text(family="serif", size=15, colour="black")) +   
      theme(legend.title = element_blank()) +   
      theme(legend.position = c(0.2, 0.7)) +
      stat_summary(fun.y = function(y) sum(y[y > 0]), fun.ymax = sum,
                   aes(label = ..ymax.., group = student), geom = "text", vjust = -1) +
      scale_y_continuous(limits = c(-4,20))
g

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM