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

如何使用ggplot2库将热图变量调整为指定顺序

Reordering Variables in ggplot2 Heatmap

Hey there! Glad to help you fix the variable order in your heatmap. The key here is to convert your x1 and x2 columns to factors with your desired custom order—this overrides ggplot's default alphabetical sorting.

Here's the updated code with the exact order you specified:

library(ggplot2)
library(reshape2)

dt <- read.table("http://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data", sep = ",")
cor.mat <- cor(dt[1:10], method = "spearman")
cor.mat.melt <- melt(cor.mat)
colnames(cor.mat.melt) <- c("x1","x2","Corelation")

# Define your custom variable order
custom_order <- c("V10", "V9", "V8", "V7", "V6", "V1", "V2", "V3", "V4", "V5")

# Convert x1 and x2 to factors with the custom order (this controls plot axis order)
cor.mat.melt$x1 <- factor(cor.mat.melt$x1, levels = custom_order)
cor.mat.melt$x2 <- factor(cor.mat.melt$x2, levels = custom_order)

# Generate the heatmap with your preferred variable order
ggplot(data = cor.mat.melt, aes(x = x1, y = x2)) + 
  geom_tile(aes(fill = Corelation)) + 
  scale_fill_gradientn(colours = rainbow(3)) + 
  geom_text(aes(x = x1, y = x2, label = round(Corelation, 2))) + 
  labs(x = "", y = "")

Quick breakdown of the fix:

  • Factor conversion: ggplot uses the levels of factor variables to determine axis order. By explicitly setting the levels to your custom sequence, you take full control of how variables are arranged.
  • Symmetric alignment: Applying the same order to both x and y axes keeps the correlation matrix heatmap symmetric, which is standard for this type of visualization.

This will produce a heatmap with variables ordered exactly as you requested: V10 → V9 → V8 → V7 → V6 → V1 → V2 → V3 → V4 → V5.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 09:38:11