Насколько мне известно, в ggplot2 нет иерархии осей. Обычно можно использовать фасеты для отделения year
от growth
, но похоже, что вы уже используете фасеты для отделения чего-то еще.
Пример того, как можно было бы использовать фасеты в этом случае:
ggplot(data=d, aes(x=interaction(growth), y=sells, fill=state)) +
geom_col(position="dodge") +
theme_bw() +
facet_grid(store ~ gamma_plot + year, labeller = label_parsed, switch = "x") +
theme(legend.title = element_blank(), legend.position="bottom",
panel.grid.major = element_blank(),
strip.placement = "outside",
legend.key.size = unit(0.10, "cm"),
legend.key.width = unit(0.15,"cm")) +
guides(fill = guide_legend(nrow = 1)) +
labs(x=expression(growth), y = "Sells")
Seeing as the above is not really a good option, I recommend looking for extention packages that offer what you seek. If you'll allow me to be so bold, there is a function in a github package I wrote that formats axes in a nested fashion. Example below:
library(ggh4x) # devtools::install_github("teunbrand/ggh4x")
ggplot(data=d, aes(x=interaction(growth, year, sep = "&"), y=sells, fill=state)) +
geom_col(position="dodge") +
theme_bw() +
facet_grid(store ~ gamma_plot, labeller = label_parsed) +
theme(legend.title = element_blank(), legend.position="bottom",
panel.grid.major = element_blank(),
legend.key.size = unit(0.10, "cm"),
legend.key.width = unit(0.15,"cm"),
axis.text.x = element_text(margin = margin(2,2,2,2))) +
scale_x_discrete(guide = guide_axis_nested(delim = "&")) +
guides(fill = guide_legend(nrow = 1)) +
labs(x=expression(growth), y = "Sells")
Edit:
With regards to the follow up question about the spacing between years; I can't think of an elegant solution but the following would get the job done. It converts the discrete axis to a continuous one.
# Precalculate interaction
d$interaction <- interaction(d$growth, d$year, sep = "&")
nudge <- 1 # How much you want to nudge
# Use ifelse to nudge position and use factor as integer
ggplot(data=d, aes(x=ifelse(as.numeric(interaction) > 2,
as.numeric(interaction) + nudge,
as.numeric(interaction)),
y=sells, fill=state)) +
geom_col(position="dodge") +
theme_bw() +
facet_grid(store ~ gamma_plot, labeller = label_parsed) +
theme(legend.title = element_blank(), legend.position="bottom",
panel.grid.major = element_blank(),
legend.key.size = unit(0.10, "cm"),
legend.key.width = unit(0.15,"cm"),
axis.text.x = element_text(margin = margin(2,2,2,2))) +
# Using a continuous axis here
scale_x_continuous(breaks = c(1,2,3 + nudge, 4 + nudge),
labels = levels(d$interaction),
guide = guide_axis_nested(delim = "&")) +
guides(fill = guide_legend(nrow = 1)) +
labs(x=expression(growth), y = "Sells")
введите описание изображения здесь