2016-09-30 132 views
0

如何在ggplot2中以正值和負值在條形圖中設置內向條形標籤?即條形標籤應該朝向0軸。面向條形圖中帶有負值的條形圖標籤(ggplot2)的「向內」

df <- data.frame(trt = c("a", "b", "c", "d"), 
       outcome = c(2.3, 1.9, 0.5, -0.5)) 

ggplot(df, aes(trt, outcome, label = outcome)) + 
    geom_bar(stat = "identity", 
      position = "identity") + 
    geom_text(vjust = "inward", color = 'red') 

vjust = "inward"obviously不是要走的方式,因爲「向內和向外是相對於圖的物理中間,而不是在0軸」。

更新:

geom_bar inward

+0

是'geom_text(vjust = C(1, 1,1,0),nudge_y = c(-0.1,-0.1,-0.1,0.4),color ='red')'類似於你之後的東西? – hrbrmstr

+0

@hrbrmstr:原則上是,外觀很好(呃,我寧願對所有'nudge_y'值使用( - )0.05,但這只是光學)。然而,我主要關心的是,我想製作許多這樣的圖形,而且我必須根據變量的值手動調整每個圖形。總體而言,並不完全。 – dpprdan

回答

2

您應該能夠設置aes映射的內部vjust來控制不同的每一行,在此基礎上無論是正面或負面的:

ggplot(df, aes(trt, outcome, label = outcome)) + 
    geom_bar(stat = "identity", 
      position = "identity") + 
    geom_text(aes(vjust = outcome > 0) 
      , color = 'red') 

enter image description here

如果你想移動標籤周圍mo重新精確(而不是僅僅vjust = 0vjust = 1,你可以從一個邏輯得到),你可以使用ifelse和更準確地定義你的位置:

ggplot(df, aes(trt, outcome, label = outcome)) + 
    geom_bar(stat = "identity", 
      position = "identity") + 
    geom_text(aes(vjust = ifelse(outcome > 0 
           , 1.5, -0.5)) 
      , color = 'red' 
      ) 

enter image description here

+0

不錯!兩者都將'vjust ='放入'aes()'(不知道這是可能的,它允許評估rhs)以及'outcome> 0'。我只想着一種將標籤進一步推向內部的方法。 (我不知道該怎麼說,但是在我的機器上,所有的標籤似乎都將像素行推到底部,因此-0.5底部的最後一行像素不在欄上,但是在白線上查看我添加到帖子中的圖表。) – dpprdan

+0

請參閱編輯以獲取更精細的控件示例。如果你想在兩個方向上進一步推動,可以在'ifelse'中選擇。 –

+0

'ifelse'當然!很好,謝謝! – dpprdan