如何让ggplot堆叠柱状图高度对应分组的最大len值
Hey there! Let's tackle this problem together. Right now your stacked bar plot is summing the len values for each dose group, but you want each bar to show the maximum len instead—like 6.8 for D0.5, which is the bigger value between VC's 6.8 and OJ's 4.2. Here's how to fix it:
Step 1: Confirm your original data
Your original data frame df2 looks like this:
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3), dose=rep(c("D0.5", "D1", "D2"),2), len=c(6.8, 15, 33, 4.2, 10, 29.5)) df2
Output:
supp dose len 1 VC D0.5 6.8 2 VC D1 15.0 3 VC D2 33.0 4 OJ D0.5 4.2 5 OJ D1 10.0 6 OJ D2 29.5
Step 2: Aggregate data to get max len per dose
We need to group the data by dose and keep only the largest len value for each group. You can use either base R or the dplyr package (I'll show both options):
Option 1: Using dplyr (cleaner syntax)
First, install and load the package if you haven't already:
install.packages("dplyr") library(dplyr)
Then aggregate the data:
df_max <- df2 %>% group_by(dose) %>% summarise(max_len = max(len), .groups = "drop")
Option 2: Using base R (no extra packages needed)
df_max <- aggregate(len ~ dose, data = df2, FUN = max) colnames(df_max)[2] <- "max_len" # Rename the column for clarity
Either way, your aggregated data df_max will look like this:
dose max_len 1 D0.5 6.8 2 D1 15.0 3 D2 33.0
Step 3: Plot the new data
Now use this aggregated data to make your bar plot—each bar will be the maximum len for its dose group:
library(ggplot2) ggplot(data = df_max, aes(x = dose, y = max_len)) + geom_bar(stat = "identity", fill = "cornflowerblue") + # Customize fill color as you like labs(title = "Maximum Length per Dose Group", x = "Dose Level", y = "Maximum Length")
Bonus: Track which supp had the max value
If you want to show which supplier (supp) corresponds to the maximum length for each dose, adjust the aggregation to keep that info:
df_max_with_supp <- df2 %>% group_by(dose) %>% filter(len == max(len)) %>% ungroup() ggplot(data = df_max_with_supp, aes(x = dose, y = len, fill = supp)) + geom_bar(stat = "identity") + labs(title = "Maximum Length per Dose (with Supplier)", x = "Dose Level", y = "Length", fill = "Supplier")
That's it! This will give you exactly the bar heights you're looking for.
内容的提问来源于stack exchange,提问作者Adrian

