简体   繁体   中英

R preserving row order ggplot2 geom_tile

I am trying to plot some categorical data and this answer is very close to what I am trying to do, however in my case I have dates in the place of countries as seen in this example. How can I create the plot with the original row order from the data.frame? It appears that even though the factors are in the same order in dat and melt.data they are not ordered sequentially on the y axis in the plot.

Here is a reproducible example:

library(reshape)
library(ggplot2)

dat <- data.frame(dates=c("01/01/2002", "09/15/2003", "05/31/2012"), Germany = c(0,1,0), Italy = c(1,0,0))
melt.data<-melt(dat, id.vars="dates", variable_name="country")

qplot(data=melt.data,
      x=country,
      y=dates,
      fill=factor(value),
      geom="tile")

Your problem is that date is stored as a character string. See str(dat) for a structure of the data.

By adding

dat$dates <- as.Date(dat$dates,"%m/%d/%Y")

after loading dat, you can get the dates in the original order.

Your problem is that dat$dates is a factor, and by default R has sorted the levels lexicographically. R does not know they are dates.

So

levels(dat$dates)
## [1] "01/01/2002" "05/31/2012" "09/15/2003"

and thererfore

order(dat$dates)
## [1] 1 3 2

If you want R to treat these as dates, then you can convert them to Date column

 dat$dates <- as.Date(as.character(dat$dates), format = '%m/%d/%Y')

  # now 
 order(dat$dates)
 ## 1 2 3

Which is what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM