andrey
andrey

Reputation: 2059

how to make bar graph of a covariance matrix with ggplot

For the following covariance matrix

ds <- read.table(header = TRUE, text ="
        Intercept        timec       timec2        timec3
    1.737039978  0.092280863 -0.041651389  2.682618e-03
        0.092280863  0.627165049 -0.120993155  6.208261e-03
      -0.041651389 -0.120993155  0.026098510 -1.416538e-03
       0.002682618  0.006208261 -0.001416538  7.949634e-05
")

I would like to create a bar graph that represents values as bars arranged in the same way as in the matrix. I try this

d <- melt(d)
p<- ggplot(d, aes(x=variable, y=value, label=value))
p<- p+ geom_bar(stat="identity")
p<- p+ facet_grid(variable~.) 
p<- p+ geom_text()
p

But it doesn't distribute the values properly in the graph.

Questions:

How would I create a bar graph for such matrix so that each value is represented as an individual bars and they are arranged in the same pattern as the values in the matrix?

enter image description here

How would

Upvotes: 0

Views: 1192

Answers (2)

jlhoward
jlhoward

Reputation: 59345

Another way to think about visualizing a covariance matrix uses a heatmap, created in ggplot using geom_tile(...).

library(ggplot2)
library(reshape2)       # for melt(...)
library(RColorBrewer)   # for brewer.pal(...)

d      <- melt(cbind(id=colnames(ds),ds),id="id")
colors <- brewer.pal(11,"Spectral")

ggplot(d, aes(x=id, y=variable, fill=value)) + 
  geom_tile()+
  geom_text(aes(label=round(value,4),color=factor(sign(value))))+
  scale_x_discrete(expand=c(0,0))+scale_y_discrete(expand=c(0,0))+
  labs(x="variable",y="variable")+
  scale_fill_gradient2(low=colors[10],mid=colors[6],high=colors[2],
                       midpoint=0, 
                       limits=c(-max(d$value),max(d$value)))+
  scale_color_manual(guide="none",values=c("red","blue"))+
  coord_fixed()

Upvotes: 2

Henrik
Henrik

Reputation: 67778

One possibility would be to create a variable ('id'), which can be used as id.vars in melt and as 'row variable' in facet_grid. You may also have a look at the facet_grid argument scales = "free_y"

library(reshape2)
library(ggplot2)

ds$id <- 1:nrow(ds)
d <- melt(ds, id.vars = "id")

ggplot(data = d, aes(x = variable, y = value)) +
  geom_bar(stat = "identity") +
  facet_grid(id ~ .)

enter image description here

Upvotes: 3

Related Questions