如何在r中为条形图的每个条形添加图像?

vngu2lb8  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(94)

我尝试使用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)

字符串

13z8s7eq

13z8s7eq1#

您需要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()

字符串


的数据

相关问题