2016-04-14 19 views
3

考慮此示例數據。r註釋幾何條上方的值

df <- data.frame(
    x = factor(c(1, 1, 2, 2)), 
    y = c(.1, .3, .2, .1), 
    grp = c("a", "b", "a", "b") 
) 

現在我創建一個使用ggplot的圖形,並用geom_text()

ggplot(data = df, aes(x, y, fill = grp, label = y)) + 
     geom_bar(stat = "identity", position = "dodge") + 
scale_y_continuous(limits=c(0,1)) + 
     geom_text(position = position_dodge(0.9)) 

如何指定所有的文本值在圖形窗口的頂部對齊完全水平標註呢?

回答

3

您可以在geom_text中指定aes(y=...)。因此,在圖形窗口上方的數字你就會有

ggplot(data = df, aes(x, y, fill = grp, label = y)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    geom_text(aes(y=Inf), position = position_dodge(0.9)) 

而且你可能希望在+ ylim(0, 4)認輸擴大繪圖區。


要匹配編輯的問題:

ggplot(data = df, aes(x, y, fill = grp, label = y)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    scale_y_continuous(limits=c(0,1)) + 
    geom_text(aes(y=0.9), position = position_dodge(0.9)) ## can specify any y=.. value 
+0

完美!雖然無窮大是不需要的,因爲它沒有符號的一半,我從你的信息中發現我可以簡單地使用y = 1。謝謝! – FlyingDutch

+0

@MvZB是的,設置'y = anynumber',它的工作原理是一樣的:) – SymbolixAU