two x axis ggplot2

hi everyone,

Is it possible to have info of two X axis in the same plot? I have the following data using mtcars dataset, and I would like to get the frequency and proportion for each of the carb categories within the 4 combinations of vs and am. That is, there will be 4 sets of bar charts, each has 6 bars. I know I can do it with facet_wrap(), but would it be possible to do it in a single plot without faceting? Thank you very much.


> ggplot(dat,aes(y=Freq,x=as.factor(carb)*as.factor(am),fill=as.factor(vs)))+stat_summary(fun='identity',geom='bar',position='dodge')
Warning messages:
1: In Ops.factor(as.factor(carb), as.factor(am)) :
  ‘*’ not meaningful for factors
2: In Ops.factor(as.factor(carb), as.factor(am)) :
  ‘*’ not meaningful for factors

I would suggest using the interaction function as shown below. In the newly created variable, the value before the decimal is carb and after is am.


ggplot(dat,aes(y=Freq,x=interaction(carb, am),fill=as.factor(vs)))+

Created on 2020-06-24 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.