2016-04-18 11 views
0

問題でgeom_labelのy値を設定:y軸の80%の高さ

Iは、入力に基づいて密度のグラフを作成する機能を持っている - 私は垂直gtableレイアウトに積み重ね、これらの3を有しています。各グラフについて、y軸が変化する。 geom_labels yの値をy軸の割合として設定して、グラフの上部に標準高さを設定したいとします。

Link to an image of the current graph with changing geom_labels y position

コード:プロットは異なるデータソースを持つ複数の層を持っている場合には規模が中に存在する別のデータセットに延伸されることがありますので

library(gtable) 
library(grid) 

mydata <- read.csv("Opta Stats EPL 2015-16.csv") 


newdata <- mydata[ which(mydata$MP.Minutes.Played > 900 & mydata$POS != 'GK' & mydata$POS != 'DEF'), ] 

PlayerX = "Harry Kane" 

x5 = 0 

DensityChart <- function(METRIC, AlphaState) { 

alphax <- AlphaState 

x5 = newdata[newdata$Player.Name == PlayerX, "INT.Interceptions"]     

q100 <- quantile(METRIC, .100) 
q0 <- quantile(METRIC, 0) 
q25 <- quantile(METRIC, .25) 
q50 <- quantile(METRIC, .5) 
q75 <- quantile(METRIC, .75) 
q95 <- quantile(METRIC, .95) 
q100 <- quantile(METRIC, 1) 


dens <- density(METRIC) 


dd <- with(dens,data.frame(x,y)) 
library(ggplot2) 
qplot(x,y,data=dd,geom="line") + geom_ribbon(data=subset(dd,x>q0 & x<q25),aes(ymax=y),ymin=0,fill="#d7191c",colour="#d7191c",alpha=alphax) + geom_ribbon(data=subset(dd,x>q25 & x<q50),aes(ymax=y),ymin=0,fill="#fdae61",colour="#fdae61",alpha=alphax) + geom_ribbon(data=subset(dd,x>q50 & x<q75),aes(ymax=y),ymin=0,fill="#ffffbf",colour="#ffffbf",alpha=alphax) + geom_ribbon(data=subset(dd,x>q75 & x<q95),aes(ymax=y),ymin=0,fill="#a6d96a",colour="#a6d96a",alpha=alphax) + geom_ribbon(data=subset(dd,x>q95 & x<q100),aes(ymax=y),ymin=0,fill="#1a9641",colour="#1a9641",alpha=alphax) + theme_minimal() + geom_vline(xintercept = x5, linetype = "longdash") + geom_label(data=newdata, aes(x=x5, y=0.02, label=x5), size=3) 
} 

p1 <- DensityChart(newdata$INT.Interceptions,0.25) 
p2 <- DensityChart(newdata$CLR.Clearances,0.25) 
p3 <- DensityChart(newdata$Tack.Won.Tackles.Won,0.25) 

g1 <- ggplotGrob(p1) 
g2 <- ggplotGrob(p2) 
g3 <- ggplotGrob(p3) 
g <- rbind(g1, g2, g3, size="first") # stack the two plots 
g$widths <- unit.pmax(g1$widths, g2$widths) # use the largest widths 
# center the legend vertically 
g$layout[grepl("guide", g$layout$name),c("t","b")] <- c(1,nrow(g)) 
grid.newpage() 
grid.draw(g) 
+0

たぶん、あなたは自分のプロット関数で 'geom_label' yの位置として' '0.8の*最大(DDます$ y)のようなものが必要?私たちがあなたの質問に単純な[再現可能な例](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)データセットを追加すると助けになりますあなたのCSVファイルはありません。 – aosmith

+0

@aosmith - ソート済み!どうもありがとう – JJGh

答えて

1

、それは常に0.8*max(y)を使用するのは実用的ではありませんプロット。この場合、グリッドビューポート内の "npc"単位でラベルを配置できるカスタムgrobを使用する方法もあります。例えば、

library(ggplot2) 
library(grid) 

tg <- grobTree(textGrob("there", y=0.8)) 
qplot(1:10, rnorm(10)) + 
    annotation_custom(tg, xmin=5, xmax=5) 

は、データまたはスケールに関係なく、y軸の80%にラベルを配置します。

enter image description here