提问人:QMan5 提问时间:11/11/2023 最后编辑:QMan5 更新时间:11/11/2023 访问量:47
如何在 r 中将图像添加到条形图的每个条形?
How to add images to each bar of the bar chart in r?
问:
我试图用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)
答:
3赞
Allan Cameron
11/11/2023
#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()
评论