如何在r中向直方图的每个条形添加图像?

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

我尝试过 ggpattern 让图像显示在栏中,但它似乎不起作用。图像不显示。相反,条形的颜色只是灰色。

library(ggplot2)
library(ggpattern)

# Sample dataframe with values and associated image URLs
df <- data.frame(
  example_column = rnorm(32),  # Replace with your actual data
  bin = cut(df$example_column, breaks = 6)
)

# Create a data frame with unique "bin" values and corresponding image paths
unique_bins <- unique(df$bin)
image_paths <- c("img1.png", "20190530153216.png", "download.png", "dstack2.png", "Dstack091.png", "Rodząca_dafnia.png")

# Ensure that there are enough image paths to match the unique "bin" values
if (length(unique_bins) > length(image_paths)) {
  stop("Not enough image paths to match unique 'bin' values")
}

# Create a data frame with unique 'bin' and image_paths
image_data <- data.frame(
  bin = unique_bins,
  image_paths = image_paths[1:length(unique_bins)]
)

# Merge the 'image_data' with the original data frame 'df' based on the 'bin' column
df <- merge(df, image_data, by = "bin", all.x = TRUE)

# Create a ggplot with images as fill patterns
p <- ggplot(df, aes(x = bin, pattern = image_paths)) +
  geom_bar_pattern(pattern = "image", color = "purple") +
  scale_pattern_manual(values = unique(df$image_paths)) +
  labs(x = "Residual Value", y = "Count") +
  theme_minimal()

# Print the plot
print(p)
r ggplot2 bar-chart histogram ggpattern
1个回答
1
投票

您需要

pattern_filename
审美和
scale_pattern_filename_identity()

ggplot(df, aes(x = bin)) +
  geom_bar_pattern(pattern = "image", aes(pattern_filename = image_paths),
                   pattern_type = "squish") +
  scale_pattern_filename_identity() +
  labs(x = "Residual Value", y = "Count") +
  theme_minimal()

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