在geom_tile中订购数据

web*_*ver 12 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))
Run Code Online (Sandbox Code Playgroud)

我想根据变量对图表进行排序V3,因为正常的绘图将根据字母V1和中的顺序对它们进行排序V2.

怎么做?

Bra*_*sen 18

我通常尝试使用级别来预先修复我的数据:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

更新:

仍然不完全清楚你的尺寸,但也许是这样的:

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

ggplot(x, aes(V1,V2,fill=V3)) + geom_tile() 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


sha*_*dow 14

作为重复问题的答案,这里是一个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)])
Run Code Online (Sandbox Code Playgroud)