rggplot2bar-charthistogramggpattern

How to add images to each bar of the bar chart in r?


I've tried to ggpattern to get the images to display in the bars, but it doesn't seem to work. The images do not display. Instead, the color of the bars is just grey.

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)

Solution

  • You need the pattern_filename aesthetic and 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()
    

    enter image description here