Steve Powell
Steve Powell

Reputation: 1698

discrete and continuous scales on same axis in facet_grid

I want to use facet_grid in ggplot2 to produce two graphs with continuous and discrete scales on the same axis - essentially my vector fac has a numeric part and a factor part.

toy=data.frame(type=xc("f f f f i i i i"),fac=c(letters[1:4],1:3,40))
ggplot(toy,aes(x=ifelse(type=="f",fac,as.numeric((fac)))))+
   geom_bar()+facet_grid(.~type,scales="free")

But it doesn't work because ggplot forces both scales to be discrete. enter image description here

As you can see from the equal spacing of 1,2,3,40 on the right-hand plot.

Upvotes: 1

Views: 3172

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98419

Two types of data in one column is not the best way to represent data.

Changed sample data for column fac to get better representation.

toy=data.frame(type=c("f", "f","f", "f", "i", "i", "i", "i"),fac=c(letters[1:4],1,5,7,40))

To get an unequal spaces for numeric values you can make two geom_bar() call, each for separate type (using subset=). For letters use data as they are but for numeric data convert fac values to character and then to numeric. facet_grid() will ensure that you have two plots. scale_x_discrete() will work for both facets - you just have to provide desired breaks= values.

library(ggplot2)
library(plyr)    
ggplot(data=toy)+
  geom_bar(subset=.(type=="f"),aes(x=fac),width=0.2)+
  geom_bar(subset=.(type=="i"),aes(x=as.numeric(as.character(fac))))+
  facet_grid(.~type,scales="free") + 
  scale_x_discrete(breaks=c("a","b","c","d",1,5,7,40))

enter image description here

Upvotes: 3

Related Questions