如何用ggplot制作协方差矩阵的条形图

时间:2014-07-05 15:39:50

标签: r graph ggplot2 bar-chart facet

对于以下协方差矩阵

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
")

我想创建一个条形图,将条形图表示为以与矩阵相同的方式排列的条形图。我试试这个

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

但它没有在图表中正确分配值。

的问题:

如何为这样的矩阵创建条形图,以便将每个值表示为单个条形,并且它们的排列方式与矩阵中的值相同?

enter image description here

怎么会

2 个答案:

答案 0 :(得分:3)

一种可能性是创建一个变量(&#39; id&#39;),可以在id.vars中用作melt,也可以用作行变量&#39;在facet_grid。您还可以查看facet_grid参数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

答案 1 :(得分:2)

考虑协方差矩阵可视化的另一种方法是使用热图,使用geom_tile(...)在ggplot中创建。

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()