R语言:如何将宽格式DataFrame适配至ggplot2热图绘制代码
Hey there! Glad you got your initial heatmap working with Pedro's help—let's get this new wide-format data sorted out for ggplot2.
The core thing to remember is that ggplot2 is designed to work best with long-format data (which your original dummy dataset used), but your DF.heatmap is in wide format. We just need to reshape it first, then we can reuse most of your existing plotting code.
Step 1: Reshape Wide Data to Long Format
We'll use the tidyr package (part of the tidyverse, which plays nicely with ggplot2) to convert your wide dataframe into a long one. We'll also add a row identifier to map each row of your original data to the y-axis of the heatmap.
# Load required libraries library(ggplot2) library(tidyr) # Reproduce your wide-format data (with set.seed for consistency) set.seed(10) DF.heatmap <- data.frame( round(runif(100, -1, 2)), round(runif(100, -1, 2)), round(runif(100, -1, 2)), round(runif(100, -1, 2)), round(runif(100, -1, 2)) ) colnames(DF.heatmap) <- c("col1", "col2", "col3", "col4", "col5") # Replace numeric values with category labels (your existing code) DF.heatmap[DF.heatmap == "-1"] <- "negative" DF.heatmap[DF.heatmap == "0"] <- "no" DF.heatmap[DF.heatmap == "1"] <- "yes" DF.heatmap[DF.heatmap == "2"] <- "other" # Reshape to long format: add row IDs and pivot columns into rows DF.long <- DF.heatmap %>% mutate(Y = paste0("Row ", seq(nrow(.)))) %>% # Create unique row labels (customize if needed) pivot_longer( cols = starts_with("col"), # Target all columns starting with "col" names_to = "X", # Name of the new column for original column names values_to = "Z" # Name of the new column for the category values )
Step 2: Plot the Heatmap
Now that we have long-format data, we can use almost the exact same ggplot code you had before. The only difference is our new DF.long dataframe maps directly to the aes() parameters:
X= your original columns (col1 to col5)Y= each row of your original dataZ= the category labels (negative/no/yes/other)
ggplot(DF.long, aes(X, Y, fill = Z)) + geom_tile(color = "white") + # Optional: add white borders between tiles for readability theme( axis.title.y = element_blank(), axis.text.y = element_blank(), # Remove this line if you want to show row labels axis.ticks.y = element_blank() ) + scale_fill_manual( values = c('#DCDCDC', '#888888', '#17334E', '#3773A4'), name = 'Z' )
Quick Notes
- If you want to display row numbers or custom row labels instead of hiding them, just remove the
axis.text.y = element_blank()line from thetheme()call. - The
color = "white"ingeom_tile()adds thin white lines between tiles, which can make the heatmap easier to read—feel free to remove it if you prefer solid blocks.
内容的提问来源于stack exchange,提问作者MDStat

