You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

含NA事件的热力图/等高线图矩阵构建及缺失事件补全咨询

Fixing Missing Combinations & Building NA-Ready Heatmaps/Contour Plots

Got it, let's tackle this problem head-on. The core issue here is that your current dplyr code isn't accounting for all possible combinations of your two categorical variables (Modeling and Discourse)—including cases where neither event occurs, which are leaving those 20 gaps in your plots. And since those gaps represent unobserved time points (not zero values), we need to explicitly code those missing combinations as NA instead of omitting them entirely.

Step 1: Fill in All Missing Categorical Combinations

The easiest way to generate every possible cross-combination of your two factors is with tidyr::complete(). This function will expand your data to include every level of Modeling paired with every level of Discourse, and fill in the numerical variable with NA for combinations that don't exist in your original data (exactly what you need).

Here's the code:

library(dplyr)
library(tidyr)

# First, ensure your categorical variables are factors (critical for complete() to work correctly)
your_data <- your_data %>%
  mutate(across(c(Modeling, Discourse), as.factor))

# Generate all possible combinations, filling missing values with NA
full_data <- your_data %>%
  complete(Modeling, Discourse, fill = list(your_numeric_var = NA))
  • Why this works: complete() creates a Cartesian product of all factor levels for Modeling and Discourse. Any pair that wasn't present in your original data gets added, with your_numeric_var set to NA (no need to manually set this—it's the default, but we explicitly include fill for clarity).

Step 2: Handle Duplicate Combinations (If Needed)

If your original data has multiple entries for the same Modeling + Discourse pair, you'll want to aggregate those first (e.g., take a mean, median, or sum) before running complete(). Just make sure to keep NA values intact:

# Aggregate duplicates (example uses mean; adjust to your needs)
aggregated_data <- your_data %>%
  group_by(Modeling, Discourse) %>%
  summarise(your_numeric_var = mean(your_numeric_var, na.rm = FALSE), 
            .groups = "drop") %>% # na.rm=FALSE ensures NA groups stay NA
  complete(Modeling, Discourse, fill = list(your_numeric_var = NA))

Step 3: Build Your Heatmap/Contour Plot Matrix

Now that your data has every possible combination (with NA for unobserved points), you can build your plots without gaps.

Heatmap with ggplot2

This will automatically handle NA values (you can customize how they look with na.value):

library(ggplot2)

ggplot(full_data, aes(x = Modeling, y = Discourse, fill = your_numeric_var)) +
  geom_tile(color = "white") + # White borders between tiles for clarity
  scale_fill_viridis_c(na.value = "gray90") + # Set NA tiles to light gray
  labs(title = "Heatmap of Numeric Variable by Modeling & Discourse",
       x = "Modeling Category", y = "Discourse Category") +
  theme_minimal()

Contour Plot (Matrix Format)

Contour plots typically require a matrix input. Convert your full dataset to a matrix first, then plot:

# Convert to a matrix (rows = Modeling, columns = Discourse)
plot_matrix <- full_data %>%
  pivot_wider(names_from = Discourse, values_from = your_numeric_var) %>%
  column_to_rownames("Modeling") %>%
  as.matrix()

# Generate contour plot (NA values are automatically skipped)
contour(plot_matrix, 
        xlab = "Modeling Categories", 
        ylab = "Discourse Categories", 
        main = "Contour Plot of Numeric Variable Matrix")

Verify Your Data

Double-check that you have all combinations by comparing the number of rows in full_data to the product of the factor levels:

# Should return TRUE if all combinations are present
nrow(full_data) == length(levels(your_data$Modeling)) * length(levels(your_data$Discourse))

This should eliminate those 20 gaps entirely, since every possible Modeling/Discourse pair is now present in your data—either with an observed value or NA for unobserved time points.

内容的提问来源于stack exchange,提问作者xyz123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:15:22