如何为R语言DataFrame添加模型分组标签列并优化分组柱状图
Solution to Your NPP Visualization Questions
Hey there! Let's break down how to solve your two problems with your NPP dataset:
1. Adding a Model Name Column to Your Dataframe
You can easily map the groups values (df1-df4) to the model names (MO-CC) using either dplyr::recode() (great for simple one-to-one mappings) or dplyr::case_when() (more flexible for complex conditions).
Method 1: Using recode() (Simplest for Your Case)
library(dplyr) # Add the new model column df <- df %>% mutate(model = recode(groups, "df1" = "MO", "df2" = "IP", "df3" = "MP", "df4" = "CC"))
Method 2: Using case_when() (Flexible for Edge Cases)
If you want to handle unexpected values in the groups column (though you probably won't need it here), this works well:
df <- df %>% mutate(model = case_when( groups == "df1" ~ "MO", groups == "df2" ~ "IP", groups == "df3" ~ "MP", groups == "df4" ~ "CC", TRUE ~ groups # Keep original value if there's an unexpected entry ))
2. Updating the ggplot2 Code for the New Column
I noticed a small bug in your original code: the geom_errorbar() had x=groups, which would misalign your error bars with the columns (since your x-axis is zone). Here's the adjusted code that uses your new model column and fixes the alignment:
df %>% mutate(zone = factor(zone,labels = c("EN","EB","DN","BF","F","Crub","hrub","Wv","av","rass","rop"))) %>% ggplot(aes(x=zone, y=mean, fill = model))+ # Switch from groups to model here geom_col(position = position_dodge(.8)) + # Fix x mapping and match dodge width to geom_col for alignment geom_errorbar(aes(ymin=mean-SE, ymax=mean+SE), width=0.4, position = position_dodge(.8))+ ggtitle("")+ scale_fill_manual(values=cbp1)+ # No need for labels now—model column has the names labs(y= an, x = "")+ theme_bw()+ theme(legend.title =element_blank())+ theme(legend.text=element_text(size=11), axis.text.y=element_text(size=11.5), axis.text.x=element_text(size=11.5), axis.title.x = element_text(size = 12), axis.title.y = element_text(size = 12))
Key Changes Explained:
- Swapped
fill = groupstofill = modelto use your new human-readable labels - Removed the
labelsargument fromscale_fill_manual()because themodelcolumn already has the correct names (MO/IP/MP/CC) - Fixed the
geom_errorbar()to remove the incorrectx=groupsparameter, and matched theposition_dodge()width togeom_col()so error bars line up perfectly with their corresponding columns
内容的提问来源于stack exchange,提问作者Hallie Sheikh
相关产品推荐
相关产品推荐

