如何使用ggpattern将图像添加到直方图?

问题描述 投票:0回答:1

我正在尝试使用 ggpattern 将图像添加到直方图,但我似乎无法让它工作。

library(ggplot2)
library(ggpattern)

image_paths <- c("img1.png", "20190530153216.png", "download.png", "dstack2.png", "Dstack091.png", "Rodząca_dafnia.png")

# Sample dataframe with values
df <- data.frame(
  example_column = rnorm(32)  # Replace with your actual data
)

# Create a histogram with images as fill patterns


p <- ggplot(df, aes(x = example_column)) +
  geom_histogram_pattern(pattern = "image", aes(pattern_filename = image_paths),
                         pattern_type = "squish") +
  scale_pattern_filename_identity() +
  labs(x = "Residual Value", y = "Count") +
  theme_minimal()

# Display the histogram
print(p)

我收到以下错误:

Error in `geom_histogram_pattern()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (32)
✖ Fix the following mappings: `pattern_filename`

我尝试添加

scale_pattern_filename_manual()
,但这也不起作用:

img1 <- system.file("img", "img1.jpg"   , package="ggpattern")
img2 <- system.file("img", "20190530153216.jpg"   , package="ggpattern")
img3 <- system.file("img", "download.jpg"   , package="ggpattern")
img4 <- system.file("img", "dstack2.jpg"   , package="ggpattern")
img5 <- system.file("img", "Dstack091.jpg"   , package="ggpattern")
img6 <- system.file("img", "Rodząca_dafnia.jpg"   , package="ggpattern")

p <- ggplot(df, aes(x = example_column)) +
  geom_histogram_pattern(pattern = "image",
                         pattern_type = "squish", bins = 6) +
  scale_pattern_filename_manual(values = c(`1` = img1, `2` = img2, `3` = img3, `4` = img4 , `5` =img5 , `6`=img6)) +
  labs(x = "Residual Value", y = "Count") +
  theme_minimal()
r ggplot2 histogram
1个回答
0
投票

正如艾伦·卡梅伦在回答你之前的问题时已经指出的那样,你必须映射到

pattern_filename
。否则
scale_pattern_filename_xxx
将不起作用。然而,如果是
geom_histogram
,那就有点特殊了。基本上我们需要将 bin 索引映射到
pattern_filename
上,这可以使用
after_stat()
来实现。其次,当然您是否需要将有效图像文件路径的向量(例如
system.file("img", "Rodząca_dafnia.jpg", package="ggpattern")
不是)传递给
values=
scale_pattern_filename_manual
参数。在下面的代码中我只是使用了 R 徽标。

library(ggplot2)
library(ggpattern)

set.seed(123)

ggplot(df, aes(x = example_column)) +
  geom_histogram_pattern(
    aes(
      pattern_filename = after_stat(
        as.character(seq_along(x))
      )
    ),
    pattern = "image",
    pattern_type = "squish",
    bins = 6
  ) +
  scale_pattern_filename_manual(
    values = rep("https://www.r-project.org/logo/Rlogo.png", 6),
    guide = "none"
  ) +
  labs(x = "Residual Value", y = "Count") +
  theme_minimal()

© www.soinside.com 2019 - 2024. All rights reserved.