右上の2つのggplotに画像を追加したいと思います。私の問題は、スケールが異なることです。そのため、プロットごとにxmin
、xmax
...を個別に指定する必要があります。
library(ggplot2)
library(png)
library(grid)
# subsetting
am0 <- subset(mtcars, am == 0)
am1 <- subset(mtcars, am == 1)
# ggplot
plt <- function(dat){
p <- ggplot(dat, aes(mpg,disp)) +
geom_point()
return(p)
}
p0 <- plt(am0)
p1 <- plt(am1)
# reading image
img <- readPNG(system.file("img", "Rlogo.png", package = "png"))
# adding image
p0 + annotation_custom(rasterGrob(img), xmin = 20, xmax = 25, ymin = 400, ymax = 450)
p1 + annotation_custom(rasterGrob(img), xmin = 30, xmax = 35, ymin = 300, ymax = 350)
私の質問は、画像のサイズと位置が一定で、プロットのスケールに依存しないように画像を追加する方法はありますか?次のようになります。
次の例に示すように、場所とスケールを指定するプロセスを自動化できるため、場所を手動で変更する必要はありません。
get.xy <- function(p) {
g_data <- ggplot_build(p)
data.frame(xmax = max(g_data$data[[1]]$x),
ymax = max(g_data$data[[1]]$y),
xmin = min(g_data$data[[1]]$x),
ymin = min(g_data$data[[1]]$y))
}
# this returns the dataframe with required x, y params for annotation_custom,
# ensuring the size and position of the image constant
get.params.df <- function(p0, p1, width, height) {
df0 <- cbind.data.frame(get.xy(p0), width=width, height=height)
df1 <- cbind.data.frame(get.xy(p1))
df1$width <- df0$width*(df1$xmax-df1$xmin)/(df0$xmax-df0$xmin)
df1$height <- df0$height*(df1$ymax-df1$ymin)/(df0$ymax-df0$ymin)
df <- rbind(df0, df1)
return(data.frame(xmin=df$xmax-df$width, xmax=df$xmax+df$width, ymin=df$ymax-df$height, ymax=df$ymax+df$height))
}
p0 <- plt(am0)
p1 <- plt(am1)
df <- get.params.df(p0, p1, width=10, height=10)
# adding image
library(gridExtra)
grid.arrange(
p0 + annotation_custom(rasterGrob(img), xmin=df[1,1],xmax=df[1,2], ymin=df[1,3], ymax=df[1,4]),
p1 + annotation_custom(rasterGrob(img), xmin=df[2,1],xmax=df[2,2], ymin=df[2,3], ymax=df[2,4])
)
より大きな画像が必要な場合は、幅と高さのパラメータのみを変更します。それ以外はすべて変更されません。
df <- get.params.df(p0, p1, width=25, height=25)
library(gridExtra)
grid.arrange(
p0 + annotation_custom(rasterGrob(img), xmin=df[1,1],xmax=df[1,2], ymin=df[1,3], ymax=df[1,4]),
p1 + annotation_custom(rasterGrob(img), xmin=df[2,1],xmax=df[2,2], ymin=df[2,3], ymax=df[2,4])
)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加