0

I am trying to adapt the approach from (ggplot2 multiple sub groups of a bar chart) but something is not as it should be. The code is:

library(grid)
MethodA= rep(c("ARIMA"), 6) 
MethodB=rep(c("LSTM"), 6)
MethodC = rep(c("ARIMA-LSTM"),6)
MethodD=rep(c("SSA"),6)
Method=c(MethodA, MethodB, MethodC, MethodD)
Measure = rep(c("RMSE", "RMSE", "MAE", "MAE", "MAPE", "MAPE"), 4)
trtest=rep(c("train", "test"), 12)
Value=sample(x = 4000:7000, size = 24, replace = TRUE)
df2 <- data.frame(Method, Measure, trtest, Value)
dodge <- position_dodge(width = 0.9)
g1 <- ggplot(data = df, aes(x = interaction(Variety, Trt), y = yield, fill = factor(geno))) +
  geom_bar(stat = "identity", position = position_dodge()) +
  #geom_errorbar(aes(ymax = yield + SE, ymin = yield - SE), position = dodge, width = 0.2) +
  coord_cartesian(ylim = c(0, 7500)) +
  annotate("text", x = 1:6, y = - 10,
           label = rep(c("Variety 1", "Variety 2", "Variety 3"), 2)) +
  annotate("text", c(1.5, 3.5), y = - 20, label = c("Irrigated", "Dry")) +
  theme_classic() +
  theme(plot.margin = unit(c(1, 1, 4, 1), "lines"),
        axis.title.x = element_blank(),
        axis.text.x = element_blank())
# remove clipping of x axis labels
g2 <- ggplot_gtable(ggplot_build(g1))
g2$layout$clip[g2$layout$name == "panel"] <- "off"
grid.draw(g2)

The problem is aslo in a sequence that interaction function generates - the sequences are not by the order - ARIMA - RMSE, MAE, MAPE, then LSTM - RMSE, MAE, MAPE ...

I would appreciate for any help. Best, Nikola

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
Nikola
  • 25
  • 4

1 Answers1

0

Instead of using interaction, it might be a lot clearer if you use facets.

Note that your example is not reproducible (your sample data has different variable names from the ones you use in your plotting code, so I had to guess which you meant to substitute):

ggplot(data = df2, aes(x = Measure, y = Value, fill = trtest)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  coord_cartesian(ylim = c(0, 7500)) +
  facet_grid(.~Method, switch = 'x') +
  theme_classic() +
  theme(strip.placement = 'outside',
        strip.background = element_blank(),
        strip.text = element_text(face = 'bold', size = 16),
        panel.spacing.x = unit(0, 'mm'),
        panel.border = element_rect(fill = NA, color = 'gray'))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • It would be great if you can explain how to group two identical graphs like above? Suppose the one above is "a" the second is of the same structure "b". What would be the steps? Thanks! – Nikola Aug 13 '22 at 16:18
  • Store each plot ( eg `p1 <- ggplot(...etc` and `p2 <- ggplot(...etc` ) then use either the `patchwork` or `cowplot` package to put the plots in the same window - e.g. `library(patchwork); p1 + p2` – Allan Cameron Aug 13 '22 at 16:20