2016-12-15 3 views
0

サンプルデータをグラフの下の値の表を追加する:はggplot2に

### Data 
df <- data.frame(year = seq(as.Date("1998/1/1"), as.Date("2012/1/1"), "years"), 
       ton = sample(200:500, 15, replace = TRUE), 
       trend = sample(50:100, 15, replace = TRUE), 
       count = sample(100:200, 15, replace = TRUE)) 

### Load the needed libraries 
library(ggplot2) 
library(scales) 
library(grid) 
library(gridExtra) 

### Make a plot 
plot1 <- ggplot(data = df, aes(x = year, y = ton)) + geom_bar(stat = "identity") + 
    scale_x_date(breaks = df$year, labels = date_format("%Y")) + 
    theme_bw() 

plot2 <- ggplot(data = df, aes(x = year, y = trend)) + geom_line() + 
    geom_point(shape = 21, size = 4, fill = "white") + 
    scale_x_date(breaks = df$year, labels = date_format("%Y")) + 
    theme_bw() 

Iはgrid.arrangeを使用して、両方のプロットを合わせ、そしてここで構文である:

grid.arrange(plot1, plot2, nrow = 2, top = "Sample data trend") 

私は次のコードとを試し表を作る(yearcount変数が、結果は良くありません。

### Create new dataframe for the table 
df1 <- data.frame(count = df$count, 
        row.names = df$year) 
df1 <- as.data.frame(t(df1)) 

### Add table below the graph 
tt <- ttheme_default(colhead=list(fg_params = list(parse=TRUE))) 
tbl <- tableGrob(df1, rows=NULL, theme=tt) 
grid.arrange(plot1, plot2, tbl, 
      nrow = 3, 
      as.table = TRUE) 

上記の構文の結果: enter image description here

質問:どのように私はそれがグラフ領域に収まるよう、そしてどのように白いスペースが最小になるように、より近いラインプロットグラフにテーブルを作ることができ?それをカスタマイズする方法があれば?

ありがとうございます。

+0

'grid.arrange'は' heights'と 'widths'パラメータを得ました。それらを使用してください。 – Roland

+0

私は次の構文を試しました: 'grid.arrange(plot1、plot2、tbl、nrow = 3、height = c(15,15,5)、widths = c(10、10、5)、as.table = TRUE) 'を返しますが、結果は同じですが、グラフの領域に表が重なって表示されます。 –

答えて

0
tt <- ttheme_default(colhead=list(fg_params = list(parse=TRUE)), 
        base_size = 10, 
        padding = unit(c(2, 4), "mm")) 
tbl <- tableGrob(df1, rows=NULL, theme=tt) 

png("E:/temp/test.png", width = 1000, height = 1000) 
grid.arrange(plot1, plot2, tbl, 
      nrow = 3, heights = c(2, 2, 0.5)) 
dev.off() 

resulting plot

+0

私はあなたの構文を試しましたが、結果のテーブルは小さいです。それを大きくする方法はありますか?どのようにして1年しか保持しない月と日をテーブルから削除できますか? –

+0

あなたが満足するまでパラメータを調整してください。要点は、デバイスのサイズが十分大きくなければならないこと、またはテーブルがデバイスに収まるのに十分なテーブル幅が必要なことです。フォーマットの日付は異なる質問です。クイック検索(またはドキュメントを読むこと)はあなたを助けます。 – Roland

+0

ありがとうございます。私のデバイスでは、構文は次のとおりです。 'ppi < - 300 png(幅= ppi * 9、高さ= ppi * 6、res = 300) grid.arrange(plot1、plot2、tbl、 nrow = 3、height = c(2,2,0)) dev.off() ' 私の最後の質問は、テーブルのタイトルを追加することは可能ですか?または、このようなもの:テーブルの上部または下部にある「1年あたりのカウント数」? –