Entering edit mode
10 months ago
peavy
•
0
Hey my code is below. Im trying to just create one legend for several graphs generated.
dvac = read.csv("2023 dvac.csv")
dvacbar = dvac[, c(1:5, 7:23),]
# Replace N/A values with 0 in columns starting with "Value"
dvacbar <- dvacbar %>%
mutate_all(~replace_na(., 0))
# Calculate the total abundance for each site and sample
siteSampleTotalAbundance <- dvacbar %>%
group_by(Site, Sample) %>%
summarise(TotalAbundance = sum(across(starts_with("Value")), na.rm = TRUE))
# Merge the total abundance back to the original data
dvacbar <- left_join(dvacbar, siteSampleTotalAbundance, by = c("Site", "Sample"))
DCDvac <- filter(dvacbar, Irrigation == "Dryland", Tillage == "Conventional")
DC=DCDvac[, c(1,5, 6:23),]
DC <- DC %>%
group_by(Site, Sample) %>%
mutate_at(vars(starts_with("Value")), ~ (. / sum(.)) * 100)
# Melt the data to long format
DCLong <- melt(DC, id.vars = c("Site", "Sample"), variable.name = "Variable")
# Create a list to store individual pie charts
pie_charts <- list()
# Loop through each unique combination of Site and Sample
for (site in unique(DCLong$Site)) {
for (sample in unique(DCLong$Sample)) {
# Subset data for the current Site and Sample
subset_data <- filter(DCLong, Site == site, Sample == sample)
# Create pie chart for the subset
pie_chart <- ggplot(subset_data, aes(x = "", y = value, fill = Variable)) +
geom_bar(stat = "identity", width = 1) +
coord_polar("y", start = 0) +
theme_void() +
labs(fill = "Variable") +
ggtitle(paste("Percentage of Abundance by Variable at", site, "-", sample)) +
theme(plot.title = element_text(hjust = 0.5))
# Append the pie chart to the list
pie_charts[[paste(site, sample, sep = "_")]] <- pie_chart
}
}
# Display the individual pie charts
gridExtra::grid.arrange(grobs = pie_charts, ncol = 3)
Is there a reason you can't use
facet_wrap
with pie charts?it probably does work. Im currently troubleshooting this error Error in
draw_panels()
: !facet_wrap()
can't use free scales withcoord_polar()
You would have to restructure your input dataframe to long format and do
facet_wrap(Site ~ Sample)
rather than using nested loops to subset your dataframe.