开发者

Order data inside a geom_tile

开发者 https://www.devze.com 2023-02-27 03:37 出处:网络
i have a data frame and i开发者_如何学运维 want to generate a geom_tile() plot from it , but I want the graph to be ordered not based on the alphabetic but based on a variable inside this data frame.

i have a data frame and i开发者_如何学运维 want to generate a geom_tile() plot from it , but I want the graph to be ordered not based on the alphabetic but based on a variable inside this data frame.

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

I want to order the plot based in the variable V3 , because the normal plotting will order them based on the alphabetic in V1 and V2 .

How this can be done ??


I usually try to use levels to fix my data before hand:

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

Order data inside a geom_tile

UPDATE:

Still not exactly clear on your dimensions, but perhaps something like:

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

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

Order data inside a geom_tile


As an answer to the duplicate question, here's a solution that uses ggplot directly and does not require changing the data.

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)])
0

精彩评论

暂无评论...
验证码 换一张
取 消