[R] Alignment of a double plot where one has a switched axis

Gavin Rudge G.Rudge at bham.ac.uk
Fri Feb 5 17:19:28 CET 2016


Hi Rgonauts,

I am plotting 3 variables from one data set on one plot.  Two of them as a stacked bar and a ratio on a completely different scale, so I  need to put one of the axes on the top of the plot for clarity.  Whilst this is not good visualisation practice, there is a valid reason why, in this case, people viewing this plot would be interested in the magnitude of the values in the stacked bars and the distribution of the ratio of them (too complex and dull to go into here).

The plot consists of horizontal stacked bars showing two values, with a dot plot showing the ratio of them, all in order of the magnitude of the ratio (this is important).  I want them to look something like the code below but with a correct alignment

I wanted to avoid something overly complex with grobs as I don't find working with them very intuitive, although this may be the only way.  I've codged together this imperfect solution from code I found about the place and was hoping someone could either suggest a much better way or help with the final task of nudging the plots to make them coherent

Thanks in advance for any help received.

GavinR

#here is my code

require(ggplot2)
require(cowplot)
require(reshape2)
require(gridExtra)
require(grid)

#my original data set looks something like this, but with many more values

Set.seed=42
df1<-data.frame(idcode=LETTERS[1:10],v1=rnorm(10,mean=30,sd=10),v2=rnorm(10,mean=10,sd=5))
str(df1)
df1$rto<-(df1$v1/df1$v2)

#melt the frame
require(reshape2)
df2<-melt(df1,id.vars=c("idcode","rto"))
df2

#oder the data by the ratio variable

df2$idcode<-reorder(df2$idcode,df2$rto)

#make the first plot
plot1<-ggplot(df2)+geom_bar(stat="identity",aes(x=idcode,y=value, fill=variable))+theme(legend.position=c(.92,.87))+coord_flip()
plot1

#make the second plot

plot2<-ggplot(df2)+geom_point(stat="identity",aes(x=idcode,y=rto))+coord_flip()+theme(panel.background = element_rect(fill="transparent"))+coord_flip()
plot2

#flip the axis with cowplot

plot2<-ggdraw(switch_axis_position(plot2, axis='x'))

#plot both on the same page

grid.newpage()

#create the layout

pushViewport(viewport(layout=grid.layout(1,1)))

#helper function to get the regions right - no idea what this does but I cribbed it from:
#http://www.sthda.com/english/wiki/ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page-r-software-and-data-visualization#create-a-complex-layout-using-the-function-viewport

define_region <- function(row, col){
  viewport(layout.pos.row = row, layout.pos.col = col)
}

#here is the plot

print(plot1,vp=define_region(1,1))
print(plot2, vp=define_region(1,1))

#has all the ingredients but how to nudge it?



More information about the R-help mailing list