Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

How to put values to R Matrix cells?

I would like to put numerical values ages into the matrix cells, while now, I have them on 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)

Current output:

enter image description here

My ideas

With geom_text but unsuccessful after the last scale

  + geom_text(aes(label = ages), size = 3)

Error in various attempts

Error: Aesthetics must be either length 1 or the same as the data (4): label, x, y, fill

Testing rawr's proposal in comment

+ geom_text(label = interaction(rep(ages, length(ages)), sep = ', '), size = 3)

Output with real-world data where you see that it repeats the first cell ID's Age for all columns; maybe, it could be enough to include the first age in the diagonal because otherwise we need two ages per cell which makes the matrix look crowded

enter image description here

Trying to adjust the wiki answer to the real case

I cannot adjust the wiki answer and its ifelse to my real case where the following geom-text works

    geom_text(label = interaction(rep(ages, length(ages)), sep = ', ')) +

OS: Debian 8.5
R: 3.1.1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Do this instead (add your labels to the data object, and then use geom_tile and then geom_text)

gg <- ggplot(data = cbind(melted_cormat,ids, ages), 
             aes(x=Var1, y=Var2, fill=value)) +
        scale_x_discrete(labels = ids ) +
        scale_y_discrete(labels = ids)
 gg + geom_raster( aes(fill=value)) +
      geom_text(  aes(x=Var1, y=Var2, label = ages), color="red", size=3)

This brings the needed data into the naming environment where the gg-functions will be able to see those named columns. The geom_raster function builds an grid of cells to which attributes ("aesthetics") such as color or text can be added. By default it mimics the base-graphics function image upon which all of the heatmap-type functions derive by coloring with a color scale constructed using the range of the "fill"-aesthetic.

Output

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...