Reputation: 7469
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")
Upvotes: 0
Views: 1072
Reputation: 115392
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
Upvotes: 1
Reputation: 32986
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.
Upvotes: 1