Trying to have just one legend for many pie charts
0
0
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)

enter image description here

R • 595 views
ADD COMMENT
0
Entering edit mode

Is there a reason you can't use facet_wrap with pie charts?

ADD REPLY
0
Entering edit mode

it probably does work. Im currently troubleshooting this error Error in draw_panels(): ! facet_wrap() can't use free scales with coord_polar()

ADD REPLY
0
Entering edit mode

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.

ADD REPLY

Login before adding your answer.

Traffic: 2364 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6