4

I have the following data and am trying to create a barplot in R with ggplot2 which have values associated with date values

conv = c(10, 4.76, 17.14, 25, 26.47, 37.5, 20.83, 25.53, 32.5, 16.7, 27.33)
click = c(20, 42, 35, 28, 34, 48, 48, 47, 40, 30, 30)

dat <- data.frame(date=c("July 7", "July 8", "July 9", "July 10", "July 11", "July 12", "July 13",
                         "July 14", "July 15", "July 16", "July 17"), click=c(click), conv=c(conv))
dat

However, when I run the following commands, the bars aren't in the proper order.

library(ggplot2)
ggplot(dat, aes(date, conv)) +  geom_bar(fill="#336699") + ylim(c(0,50)) +
        opts(title="") +
        opts(axis.text.y=theme_text(family="sans", face="bold", size=10)) +
        opts(axis.text.x=theme_text(family="sans", face="bold", size=8)) +
        opts(plot.title = theme_text(size=15, face="bold")) +
        xlab("") + ylab("")

The variable date is properly ordered from July 7 to July 17, and don't know why ggplot2 has a problem with this. Is there a quick function to fix this problem without having to reorder the data in the original data set.

Etienne Low-Décarie
  • 13,063
  • 17
  • 65
  • 87
ATMathew
  • 12,566
  • 26
  • 69
  • 76
  • 2
    I notice you have already accepted an answer that doesn't actually work. Which is your prerogative, but it doesn't actually motivate anyone to post the correct answer. – Andrie Jul 18 '11 at 20:24
  • Sure, the answer was wrong, but it pointed me to the right solution. Therefore, it was helpful. – ATMathew Jul 18 '11 at 20:28
  • 1
    Just because it pointed you to the right solution doesn't mean it will do the same for others. – Joshua Ulrich Jul 18 '11 at 20:30
  • Related question: http://stackoverflow.com/q/3744178/602276 – Andrie Jul 18 '11 at 20:51

1 Answers1

4

The reason that your sort order does not work is because you have a character string, not dates. Your best option is to convert your dates into date format:

dat$date <- as.Date(paste(dat$date, "2011"), format="%b %d %Y")

ggplot(dat, aes(as.character(date), conv)) +  geom_bar(fill="#336699") + 
    ylim(c(0,50)) +
    opts(title="") +
    opts(axis.text.y=theme_text(family="sans", face="bold", size=10)) +
    opts(axis.text.x=theme_text(family="sans", face="bold", size=8, angle=90)) +
    opts(plot.title = theme_text(size=15, face="bold")) +
    xlab("") + ylab("")

enter image description here

Andrie
  • 176,377
  • 47
  • 447
  • 496