2016-01-13 6 views
6

ggplot2::ggplot()で作成したプロットに少しのサマリーテーブルを追加しようとしました。テーブルはgridExtra::tableGrob()を介して保存されたggplotオブジェクトに追加されます。gridExtraとannotation_custom()でggplotにテーブルを追加するとy軸の制限が変わる

私の問題は、これが私の元のプロットのy制限を変えているようだということです。 ylim()を介して再度制限を指定しなくてもそれを回避する手段はありますか?ここで

がChickWeightデータセットを使用して問題のための最小限の例です。

# load packages 
require(ggplot2) 
require(gridExtra) 

# create plot 
plot1 = ggplot(data = ChickWeight, aes(x = Time, y = weight, color = Diet)) + 
     stat_summary(fun.data = "mean_cl_boot", size = 1, alpha = .5) 
plot1 
# create table to add to the plot 
sum_table = aggregate(ChickWeight$weight, 
         by=list(ChickWeight$Diet), 
         FUN = mean) 
names(sum_table) = c('Diet', 'Mean') 
sum_table = tableGrob(sum_table) 

# insert table into plot 
plot1 + annotation_custom(sum_table) 

ylim problem with annotation_custom()

EDIT: 私はちょうどstat_summary()の問題であると思われることを考え出しました。別のジオム/レイヤーを使用すると、元のプロットと同じように制限が残ります。そのため他の実施例:

plot2 = ggplot(data = ChickWeight, aes(x = Time, y = weight, color = Diet)) + 
     geom_jitter() 
plot2 
plot2 + annotation_custom(sum_table) 

ylim problem with annotation_custom()

+0

私はこの問題についてはよく分かっていませんが、 'stat_summary'の問題ではないと思います。' plot2 + stat_summary(fun.data = "mean_cl_boot"、size = 1、alpha = .5) + annotation_custom(sum_table) 'あなたのylimは保存されます。 – George

+0

それは面白いです。 'geom = 'pointrange''(デフォルトで' stat_summary'が使用する)の代わりにデータ範囲全体のy制限を設定します。だから私が正しく見れば、私の最初の例では、ylimは(pointrangeからの)要約され表示された値の範囲に調整されますが、 'annotation_custom'を追加すると再びデータ全体の範囲が使用されます。 – abel

答えて

4

plot1するY範囲は、annotation_customが元aes文ないstat_summary()で使用される変更されたデータフレームからその美学を取ることである理由plot2異なります。 2つのプロットのy範囲が同じになるようにするには、annotation_customが元のデータからその美学を取得するのを止めます。つまり、stat_summary()の内部にaes()を移動します。

# load packages 
require(ggplot2) 
require(gridExtra) 

# create plot 
plot1 = ggplot(data = ChickWeight) + 
     stat_summary(aes(x = Time, y = weight, color = Diet), fun.data = "mean_cl_boot", size = 1, alpha = .5) 
plot1 

# create table to add to the plot 
sum_table = aggregate(ChickWeight$weight, 
         by=list(ChickWeight$Diet), 
         FUN = mean) 
names(sum_table) = c('Diet', 'Mean') 
sum_table = tableGrob(sum_table) 

# insert table into plot 
plot2 = plot1 + annotation_custom(sum_table, xmin = 10, xmax = 10, ymin = 200, ymax = 200) 
plot2 

enter image description here

ところで、二つのグラフは、全く同じY-rangeを与えない理由は、stat_summary()でブートストラップ機能です。実際、p1を繰り返しプロットすると、y範囲にわずかな変化が見られることがあります。または、ビルドデータのy範囲を確認してください。

ggplot_build(plot1)$layout$panel_ranges[[1]]$y.range 
ggplot_build(plot2)$layout$panel_ranges[[1]]$y.range 

ggplotは時間を描画するまでの機能を評価していないことを思い出してください - それぞれの時間P1またはP2が描かれ、新しいブートストラップサンプルが選択されています。

関連する問題