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

R语言Correspondence analysis plot文本标签颜色调整求助

解决R语言对应分析图标签颜色自定义问题

用ca包默认的plot()函数直接绘图时,确实没法直接获取标签坐标,得从分析结果里手动提取坐标数据,再自定义绘制标签。以下是具体实现步骤:

步骤1:提取坐标数据

ca函数返回的结果里,行(水果)的坐标存在ca_results$row$coord,列(食物)的坐标存在ca_results$col$coord,直接提取即可。

步骤2:自定义绘图

先画空画布,再用text()函数逐个添加标签,给指定标签设置颜色:

observed <- matrix(c(  53, 15, 16, 45, 21, 5, 46, 11, 54, 40, 87, 43, 4, 19, 22, 16,
  19, 1, 3, 20, 7, 3, 6, 5, 24, 12, 29, 13, 3, 3, 4, 5,
  21, 1, 5, 26, 7, 4, 16, 5, 22, 19, 23, 21, 2, 13, 16, 18,
  153, 15, 45, 150, 46, 16, 107, 49, 180, 174, 212, 112, 24, 44, 47, 77,
  3, 1, 3, 11, 2, 0, 4, 1, 3, 9, 5, 8, 1, 3, 0, 4,
  4, 1, 5, 16, 4, 0, 3, 3, 16, 9, 9, 5, 1, 1, 2, 10,
  72, 10, 12, 67, 25, 6, 69, 24, 90, 79, 88, 59, 5, 30, 25, 23,
  25, 4, 8, 14, 17, 1, 23, 4, 29, 26, 31, 7, 4, 12, 18, 10,
  68, 6, 16, 43, 31, 2, 51, 26, 66, 54, 70, 17, 12, 29, 51, 20,
  5, 0, 2, 6, 5, 0, 6, 0, 9, 9, 9, 5, 1, 2, 2, 2,
  98, 10, 36, 113, 38, 15, 42, 38, 99, 89, 162, 75, 15, 28, 44, 37
), nrow=11, byrow=TRUE)

rownames(observed) <- c("apple", "banana", "grape", "olive",
                         "strawberry", "watermelon", "apricot", "plum", "orange",
                         "kiwi", "pomegranate")

colnames(observed) <- c("sandwich", "water", "bread",
                         "lettuce", "potato", "tomato",
                         "onion", "garlic", "pepper",
                         "broccoli", "mushroom", "jalapeno",
                         "prune", "avokado", "melon",
                         "lemon")

library(ca)
ca_results <- ca(observed)

# 提取坐标
row_coords <- ca_results$row$coord
col_coords <- ca_results$col$coord

# 设置颜色规则
row_colors <- ifelse(rownames(row_coords) == "strawberry", "red", "black")
col_colors <- ifelse(rownames(col_coords) == "lemon", "yellow", "black")

# 绘制空画布,匹配原plot的坐标轴范围
plot(ca_results, type = "n")

# 添加行标签(水果)
text(row_coords[,1], row_coords[,2], labels = rownames(row_coords), 
     col = row_colors, cex = 0.8)

# 添加列标签(食物)
text(col_coords[,1], col_coords[,2], labels = rownames(col_coords), 
     col = col_colors, cex = 0.8)

扩展:批量设置多个标签颜色

如果要给多个标签设不同颜色,可以用case_when(需要加载dplyr包)或者嵌套ifelse:

library(dplyr)
row_colors <- case_when(
  rownames(row_coords) == "strawberry" ~ "red",
  rownames(row_coords) == "kiwi" ~ "green",
  TRUE ~ "black"
)

col_colors <- case_when(
  rownames(col_coords) == "lemon" ~ "yellow",
  rownames(col_coords) == "tomato" ~ "red",
  TRUE ~ "black"
)

这样就能精准控制每个标签的颜色了,再也不用纠结坐标获取的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 11:02:09