将geom_label y值设置为y轴的80%高度

时间:2016-04-18 21:40:09

标签: r ggplot2

问题:

我有一个基于输入创建密度图的函数 - 我有3个垂直堆叠在gtable布局中。对于每个图,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)

1 个答案:

答案 0 :(得分:1)

当绘图具有多个具有不同数据源的图层时,使用0.8*max(y)并不总是切实可行,因为绘图可能会被绘图中存在的另一个数据集拉伸。在这种情况下,另一种方法可以是使用自定义grob,其中可以将标签以“npc”单位放置在网格视口中。例如,

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