2013-02-27 34 views
1

我可以請尋求你的幫助來標記barplot與像下圖GGPLOT2:如何使用ggplot在-ve和+ ve值的條的另一側標註barplot?

enter image description here

我使用下面的代碼,以獲得附加的情節:

library(ggplot2) 

test <- data.frame(x = c("Moderately Poor", "Deeply Poor", "Deeply & Intensely Poor", "Intensely Poor", "Overall Poverty"), y = c(0.024, -0.046, -0.025, -0.037, -0.083)) 

test$colour <- ifelse(test$y < 0, "firebrick1", "steelblue") 
test$hjust <- ifelse(test$y > 0, 1.03, -0.03) 

ggplot(test, aes(x, y, label = x, hjust = hjust)) + 
    geom_text(aes(y = 0, colour = colour)) + 
    geom_bar(stat = "identity", aes(fill = colour)) 

last_plot() + coord_flip() + labs(x = "", y = "") + 
    scale_x_discrete(breaks = NA) + theme_bw() + 
    opts(legend.position = "none") 

我只是想知道如何獲得每個欄上的第二個數字標籤?

謝謝,

+2

不[**這**](http://learnr.wordpress.com/ 2009/06/01/ggplot2-positioning-of-barplot-category-labels /)help? – Arun 2013-02-27 08:55:08

+0

或[** this **](http://stackoverflow.com/questions/11938293/how-to-label-a-barplot-bar-with-positive-and-negative-bars-with-ggplot2) – Arun 2013-02-27 09:00:39

+0

@ Arun是否可以在每個反映該值的欄上添加另一個標籤? – 2013-02-28 01:42:46

回答

3

R圖形,包括ggplot2,是筆在紙上,即layers(各geom_...)將按順序繪製。

所以,如果你想在geom_bar的頂部有geom_text,那麼geom_text需要在geom_bar之後。

更新爲ggplot2 0.9.3(當前版本)

ggplot(test, aes(x, y)) + 
    geom_text(aes(y = 0, colour = colour, hjust =hjust, label = x), size=4.5) + 
    geom_bar(stat = "identity", aes(fill = colour)) + 
    geom_text(colour ='black', 
    aes(label = paste(formatC(round(y*100, 2), format='f', digits=2),'%'), 
     hjust = ifelse(y>0,1,0))) + 
    coord_flip() + labs(x = "", y = "") + 
    scale_x_discrete(breaks = NULL) + theme_bw() + 
    theme(legend.position = "none") 

產生

enter image description here

相關問題