问题描述
|
我有一个数据框,我想从中生成一个
geom_tile()
图,但是我希望该图的排序不是基于字母而是基于此数据框中的变量。
structure(list(V1 = c(\"a\",\"y\",\"w\",\"p\",\"v\",\"h\",\"i\"),V2 = c(\"r\",\"q\",\"m\",\"l\",\"g\"),V3 = c(
\"5\",\"2\",\"9\",\"1\",\"3\",\"0\")),.Names = c(\"V1\",\"V2\",\"V3\"),class = \"data.frame\",row.names = c(NA,-8L))
我想根据变量V3
对图进行排序,因为正常的绘图将根据V1
和V2
中的字母对它们进行排序。
如何做到这一点?解决方法
我通常会尝试先使用级别来修复我的数据:
x <- structure(list(V1 = c(\"a\",\"y\",\"w\",\"p\",\"v\",\"h\",\"i\"),V2 = c(\"r\",\"q\",\"m\",\"l\",\"g\"),V3 = c(
\"5\",\"2\",\"9\",\"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()
更新:
您的尺寸仍然不完全清楚,但可能类似:
x$V2 <- factor(x$V2,levels=(x$V2)[order(x$V3)])
ggplot(x,V2,fill=V3)) + geom_tile()
,作为对重复问题的解答,这是一个直接使用ggplot
并且不需要更改数据的解决方案。
x <- structure(list(V1 = c(\"a\",V3 = c( \"5\",]
ggplot(x,fill=V3)) + geom_tile() +
scale_x_discrete(limits=(x$V1)[order(x$V3)]) +
scale_y_discrete(limits=(x$V2)[order(x$V3)])