如何在R中基于因子变量的众数填充geom_tile绘制热图?
Hey there, let's fix this heatmap issue for you! The problem with your original code is that when you use the raw ChickWeight data with geom_tile(), each cell (combination of Time and Diet) has multiple weight_group entries. ggplot doesn't automatically calculate the mode for you—it just draws all those tiles on top of each other, and you end up seeing the last one in the dataset. That's why your bottom-right cell isn't showing the mode (1) like you expected.
Here's how to fix it step by step:
1. Create a function to calculate mode
R doesn't have a built-in mode function, so let's make one that grabs the most frequent value in a vector (works perfectly for your case where there's a single clear mode):
get_mode <- function(x) { unique_vals <- unique(x) unique_vals[which.max(tabulate(match(x, unique_vals)))] }
2. Aggregate data to get the mode per (Time, Diet) group
We'll use dplyr to group the data by Time and Diet, then compute the mode of weight_group for each group:
library(dplyr) library(ggplot2) # Your original data prep (kept unchanged) data(ChickWeight) ChickWeight$Time <- ifelse(ChickWeight$Time >= 10, 1, 0) ChickWeight <- ChickWeight %>% mutate(weight_group = ntile(weight, 3)) %>% mutate(across(c(Diet, Time, weight_group), as.factor)) # Aggregate to get modal weight group for each Time-Diet pair chick_summary <- ChickWeight %>% group_by(Time, Diet) %>% summarise(modal_weight_group = get_mode(weight_group), .groups = "drop")
3. Plot the heatmap with aggregated data
Now use this summarized dataset for your heatmap—each cell will now use the mode of weight_group instead of an overlapping, random value:
ggplot(chick_summary, aes(x = Time, y = Diet, fill = modal_weight_group)) + geom_tile(color = "white") + # Add white borders to make cells easier to distinguish labs(fill = "Weight Group (Mode)")
Verify the result
If you run filter(chick_summary, Diet == 1, Time == 1), you'll confirm that modal_weight_group is indeed 1, so the bottom-right cell will now show the pink color you expected.
内容的提问来源于stack exchange,提问作者Maria

