【发布时间】:2016-11-01 05:55:40
【问题描述】:
我想将数值 ages 放入矩阵单元格中,而现在,我将它们放在 x-ais 上
library("ggplot2")
library("reshape2")
mydata <- mtcars[, c(1,3,4,5,6,7)]
cormat <- round(cor(mydata),2)
melted_cormat <- melt(cormat)
ids = c(1, 2, 3, 4, 5,6)
ages = c(11, 22, 33, 44, 55,66)
ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) +
scale_x_discrete(labels = ids ) +
scale_y_discrete(labels = ids)
当前输出:
我的想法
使用geom_text,但在最后一次缩放后不成功
+ geom_text(aes(label = ages), size = 3)
各种尝试都出错
Error: Aesthetics must be either length 1 or the same as the data (4): label, x, y, fill
在评论中测试 rawr 的提案
+ geom_text(label = interaction(rep(ages, length(ages)), sep = ', '), size = 3)
使用真实数据的输出,您会看到它对所有列重复第一个单元格 ID 的年龄;也许,在对角线上包含第一个年龄就足够了,否则我们需要每个单元格两个年龄,这使得矩阵看起来很拥挤
尝试根据实际情况调整 wiki 答案
我无法将 wiki 答案及其 ifelse 调整为以下 geom-text 工作的真实案例
geom_text(label = interaction(rep(ages, length(ages)), sep = ', ')) +
操作系统:Debian 8.5
R:3.1.1
【问题讨论】:
-
函数需要返回值...子集用于交互使用,即不在函数内部...
-
改用
geom_text(label = interaction(rep(ids, length(ages)), ages, sep = ', '), size = 3)。你有 36 个数据点,你需要 36 个标签 -
这是一个相关矩阵吗?或者如果对角线值被定义为 1(或 0),那么它们都将具有基于
value的统一颜色 -
所以只有对角线标记?
ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) + geom_tile() + geom_text(label = ifelse(melted_cormat$Var1 == melted_cormat$Var2, ages, ''))使用您想要的标签创建一个列并使用geom_text(label = column_with_labels)可能会更简单 -
为什么
interaction需要调整?添加一列以确保您需要的标签排列整齐melted_cormat$label <- with(melted_cormat, ifelse(Var1 == Var2, ages, ''))并使用geom_text(labels = melted_cormat$label)
标签: r