2014-10-30 75 views
5

我想繪製兩年不同年份的躲避barplot,並相應地將收入數字放在條的頂部。在嘗試了一些建議後,我發現在這裏,我仍然不能完全得到我想要的(所有數字都顯示在中間的酒吧/列的中間,而不是均勻分佈)。任何建議,將不勝感激。謝謝!使用ggplot2在facet躲避的barplot上添加文本

我的最新嘗試

# Disable scientific notation 
options("scipen" = 100, "digits" = 1) 

censusData <- structure(list(Year = c(2012L, 2007L, 2012L, 2007L, 2012L, 2007L, 
             2012L, 2007L, 2012L, 2007L, 2012L, 2007L, 2012L, 2007L, 2012L, 
             2007L, 2012L, 2007L, 2012L, 2007L, 2012L, 2007L, 2012L, 2007L 
            ), County = c("A", "A", "B", "B", "C", "C", "Sum", "Sum", "A", 
             "A", "B", "B", "C", "C", "Sum", "Sum", "A", "A", "B", "B", "C", 
             "C", "Sum", "Sum"), variable = structure(c(1L, 1L, 1L, 1L, 1L, 
             1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 
             3L, 3L, 3L), .Label = c("Total_Revenue", "Crop_Revenue", "Livestock_Revenue" 
            ), class = "factor"), value = c(1645.51, 1203.806, 68.911, 60.949, 
             923.163, 525.918, 2637.584, 1790.673, 1069.497, 787.459, 47.157, 
             38.735, 825.050228, 470.024, 1941.704228, 1296.218, 576.013, 
             416.347, 21.754, 22.214, 98.112772, 55.894, 695.879772, 494.455 
            )), row.names = c(NA, -24L), .Names = c("Year", "County", "variable", 
             "value"), class = "data.frame") 

# Dodged barplot 
qbarplot_yr_1 <- ggplot(censusData, aes(County, value)) + facet_grid(. ~ Year) + 
    geom_bar(aes(fill = variable), position = "dodge", stat="identity") + 
    xlab("County") + ylab("Revenue (Million USD)") + 
    scale_fill_discrete(name = 'Legend', labels=c("Total", "Crop", "Livestocks")) + 
    theme(axis.ticks.x = element_blank()) + 
    theme(panel.background = element_rect(colour='dark grey')) + 
    theme(strip.text.x = element_text(size = 20, face="bold"), 
     strip.background = element_rect(colour="dark grey")) 

# Add text on top of the bar 
qbarplot_yr_1 + geom_text(data = censusData, 
          aes(x = County, y = value + 150, label = format(value, nsmall = 0, scientific = FALSE)), 
          color="blue") 

**ggplot2 output**

回答

15

你需要閃避的文本值也是如此。嘗試

qbarplot_yr_1 + geom_text(data = censusData, 
     aes(x = County, group=variable, y = value + 150, 
     label = format(value, nsmall = 0, digits=1, scientific = FALSE)), 
     color="blue", position=position_dodge(.9), hjust=.5) 

我們還需要group=因此它知道閃避的值。

+0

謝謝。不知道爲什麼我在我的'geom_text()'調用中忽略了'group',但這救了我! – Steven 2017-04-10 17:22:15