Raffael
Raffael

Reputation: 20045

ggplot with X axis having multiple levels

Think of a data frame providing three columns:

I want to plot value by year/month in its natural order. But so far I didn't find a good way to accomplish this in ggplot. Below you'll find a simplified example showing my desired result but by applying a workaround - concatenating year and month or a and b in the example. But this solution brings already several disadvantages with it.

Is there a generic way to accomplish this in ggplot?

> library(ggplot2)

> df <- data.frame(a = c(1,1,1,2,2,2), b = c(1,2,3,1,2,3), v = 1:6)

> df
  a b v
1 1 1 1
2 1 2 2
3 1 3 3
4 2 1 4
5 2 2 5
6 2 3 6

> dfX <- data.frame(ab = paste(df$a,df$b), v = df$v)

> dfX
   ab v
1 1 1 1
2 1 2 2
3 1 3 3
4 2 1 4
5 2 2 5
6 2 3 6

> ggplot(dfX, aes(x = ab, y = v)) + geom_point()

enter image description here

How would I get the above plot using df directly?

Upvotes: 1

Views: 2837

Answers (3)

Didzis Elferts
Didzis Elferts

Reputation: 98599

If you have Year and Month values then my approach would be to paste them together with day of 1 and then convert to Date object. Then data will be plotted in right order. If you need only Month and Year in x axis it can be modified with scale_x_date() and date_format() of library scales.

df2<-data.frame(year=c(2011,2011,2011,2012,2012,2012),
                 month=c(10,11,12,1,2,3),value=1:6)
df2$dm<-as.Date(paste(df2$year,df2$month,"1",sep="/"))

library(scales)
ggplot(df2,aes(dm,value))+geom_point()+
  scale_x_date(labels=date_format("%Y-%m"))

Upvotes: 2

Julius Vainora
Julius Vainora

Reputation: 48251

paste works here too:

ggplot(df, aes(x = paste(a, b), y = v)) + geom_point()

Upvotes: 2

agstudy
agstudy

Reputation: 121626

Maybe using interaction:

ggplot(dfX, aes(x = interaction(a,b), y = v)) + geom_point()

Upvotes: 2

Related Questions