在geom_tile中订购数据

时间:2011-04-19 08:38:33

标签: r ggplot2

我有一个数据框,我想从中生成geom_tile()图,但我希望图表不是基于字母顺序排序,而是基于此数据框内的变量。

structure(list(V1 = c("a", "y", "w", "p", "v", "h", "i"), 
    V2 = c("r", "w", "q", "m", "l", "q", "g"), V3 = c( 
    "5", "2", "9", "2", "1", "3", "0")), .Names = c("V1", "V2", 
"V3"), class = "data.frame", row.names = c(NA, -8L))

我想根据变量V3订购图表,因为正常的绘图会根据V1V2中的字母顺序排序。

如何做到这一点??

2 个答案:

答案 0 :(得分:17)

我通常会尝试使用关卡来修复我的数据:

x <- structure(list(V1 = c("a", "y", "w", "p", "v", "h", "i"), 
    V2 = c("r", "w", "q", "m", "l", "q", "g"), V3 = c( 
    "5", "2", "9", "2", "1", "3", "0")), .Names = c("V1", "V2", 
"V3"), class = "data.frame", row.names = c(NA, -8L))

x <- x[1:7,]

x$V1 <- factor(x$V1, levels=(x$V1)[order(x$V3)])

# Note it's not an ordered factor, it's a factor in the right order

ggplot(x, aes(V1, V3)) + geom_tile()

enter image description here

更新:

仍然不完全清楚您的尺寸,但可能类似于:

x$V2 <- factor(x$V2, levels=(x$V2)[order(x$V3)])

ggplot(x, aes(V1,V2,fill=V3)) + geom_tile() 

enter image description here

答案 1 :(得分:13)

作为duplicate question的答案,这是一个直接使用ggplot并且不需要更改数据的解决方案。

x <- structure(list(V1 = c("a", "y", "w", "p", "v", "h", "i"), 
                    V2 = c("r", "w", "q", "m", "l", "q", "g"), 
                    V3 = c( "5", "2", "9", "2", "1", "3", "0")), 
               .Names = c("V1", "V2", "V3"), class = "data.frame", 
               row.names = c(NA, -8L))

x <- x[1:7,]

ggplot(x, aes(V1, V2, fill=V3)) + geom_tile() +
  scale_x_discrete(limits=(x$V1)[order(x$V3)]) + 
  scale_y_discrete(limits=(x$V2)[order(x$V3)])
相关问题