2017-06-04 9 views
2

私は何か同じものを見つけなかったので、試してみることなしにこれを尋ねます。私はこれを謝罪します。棒グラフの下の値の表を表示

thisバープロットから:

df <- structure(list(year = 2002:2005, work = c(1L, 2L, 3L, 2L), confid = c(8L, 
5L, 0L, 6L), jrs = c(0L, 3L, 4L, 5L)), .Names = c("year", "work", 
"confid", "jrs"), class = "data.frame", row.names = c(NA, -4L 
)) 

library(ggplot2) 
library(reshape) 
md <- melt(df, id=(c("year"))) 
temp.plot <- ggplot(data=md, aes(x=year, y=value, fill=variable)) + 
    geom_bar(stat="identity")+ 
    theme(axis.text.x=element_text(angle=90))+ 
    ggtitle("Score Distribtion") 

temp.plot 

私はそれがすべての変数についてbarplotであるとして、毎年の下に値を持つようにggplot2を使用して、任意の簡単な方法があるかどうかお尋ねしたいと思います。 ここにダミー出力例を示します。 enter image description here

答えて

8

各バーにカウントをプロットする方が良いかもしれません。たとえば、次のように

library(ggplot2) 
theme_set(theme_classic()) 

ggplot(data=md, aes(x=year, y=value, fill=variable)) + 
    geom_bar(stat="identity") + 
    ggtitle("Score Distribution") + 
    geom_text(aes(label=value), position=position_stack(vjust=0.5), colour="white") + 
    labs(fill="") 

enter image description here

あなたはまだプロットの下にテーブルをしたい場合は、私は簡単な方法を知りませんが、あなたのように伝説を抽出し、テーブルに別々のtableGrobを作成することができます別のgrob(グラフィックオブジェクト)を作成し、各パーツを別々にレイアウトします。さまざまなパーツをレイアウトするには手作業で微調整する必要がありますが、グリッドグラフィックスを私が理解している人はそれを自動化できるかもしれません。ここでは例です:

library(grid) 
library(gridExtra) 

# Function to extract legend 
# https://stackoverflow.com/a/13650878/496488 
g_legend <- function(a.gplot){ 
    tmp <- ggplot_gtable(ggplot_build(a.gplot)) 
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") 
    legend <- tmp$grobs[[leg]] 
    return(legend)} 

p = ggplot(data=md, aes(x=year, y=value, fill=variable)) + 
    geom_bar(stat="identity")+ 
    #theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=0.5))+ 
    ggtitle("Score Distribution") + 
    labs(fill="") 

# Extract the legend as a separate grob 
leg = g_legend(p) 

# Create a table grob 
tab = t(df) 
tab = tableGrob(tab, rows=NULL) 
tab$widths <- unit(rep(1/ncol(tab), ncol(tab)), "npc") 

# Lay out plot, legend, and table grob 
grid.arrange(arrangeGrob(nullGrob(), 
         p + guides(fill=FALSE) + 
          theme(axis.text.x=element_blank(), 
           axis.title.x=element_blank(), 
           axis.ticks.x=element_blank()), 
         widths=c(1,8)), 
      arrangeGrob(arrangeGrob(nullGrob(),leg,heights=c(1,10)), 
         tab, nullGrob(), widths=c(6,20,1)), 
      heights=c(4,1)) 

enter image description here

関連する問題