Reorder ggplot2 rows with dates on the x axis

I have the following data and I'm trying to create a barplot in R with ggplot2 that 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 are not in the correct 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 date of the variable is correctly ordered from July 7 to July 17 and does not know why the problem with ggplot2 is related to this. Is there a quick feature to fix this problem without having to reorder the data in the original dataset.

+4
source share
1 answer

The reason your sort order does not work is because you have a character string, not a date. Your best option is to convert your dates to 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

+4
source

All Articles