Чтобы получить горизонтальный градиент в rasterGrob
объекте, вы должны определить свое изображение следующим образом:
> matrix(c("lightgreen","yellow","orange","red"), nrow = 1)
[,1] [,2] [,3] [,4]
[1,] "lightgreen" "yellow" "orange" "red"
Вместо этого:
> c("lightgreen","yellow","orange","red")
[1] "lightgreen" "yellow" "orange" "red"
Или это:
> matrix(c("lightgreen","yellow","orange","red"), ncol = 1)
[,1]
[1,] "lightgreen"
[2,] "yellow"
[3,] "orange"
[4,] "red"
Что касается маркировки за пределами области диаграммы, вы можете сделать это, если отключите отсечение в декартовых координатах:
# define raster grob with horizontal gradient
g <- rasterGrob(matrix(c("lightgreen","yellow","orange","red"), nrow = 1),
width=unit(1,"npc"), height = unit(1,"npc"),
interpolate = TRUE)
ggplot(dataset, aes(myVariable1)) +
scale_x_continuous(expand = c(0, 0), limits = c(0, maxVariable1)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, 10)) +
annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_vline(aes(xintercept=myVariable1), color="red", size=1) +
# no need to adjust y value; we can use the maximum limit set above,
# & assign a negative number to vjust instead;
# also, since it's now sitting atop the chart, it'll make more sense
# to align the label with myVariable, rather than dodge it to one side.
annotate("text", x=myVariable1, y=10, label="Me", colour="red",
vjust = -0.5) +
# turn off clipping here
coord_cartesian(clip = "off") +
# add plot.margin specification to theme, with large value for top margin
# (5.5 is the default for all four sides)
theme(
axis.title.y=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank(),
plot.margin = unit(c(20, 5.5, 5.5, 5.5), "pt")
)