Как создать график по двум подгруппам с помощью интеракции () в ggplot (комбинация нескольких графиков) - PullRequest
3 голосов
/ 10 июля 2020

Я пытаюсь создать графики по двум подгруппам, как на картинке ниже ( ggplot2 несколько подгрупп гистограммы ). Однако я хотел бы сделать это для комбинации графиков.

enter image description here

When I tried to do that, instead of having the categories clearly separated (like in the example with Irrigated/Dry and Variety1/Variety 2), my variables "growth" and "year" are being collapsed together.

I am having trouble incorporating into my code this tiny modification. I would like for my variable year to be just like "Irrigated/Dry", and the variable growth as "Variety1/Variety2" Right now, this is how the plot looks like:

enter image description here

Here is my code:

library(ggplot2)

#Creates the data

d 

EDITED:

The two solutions given to my question were great and I really appreciate it. I have decided to alter the plot a little and have an interaction between gamma_plot and growth instead. I could not make R understand that gamma_plot was an expression. Any ideas?

введите описание изображения здесь

#Creates the plot using teunbrand's code :)

ggplot(data=d, aes(x=interaction(growth, gamma_plot, sep = "&"), y=sells, fill=year)) + 
  geom_col(position="dodge") +
  theme_bw() +
  facet_grid(store ~ state, 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")

Ответы [ 2 ]

2 голосов
/ 10 июля 2020

Как насчет этого варианта:



library(ggplot2)


ggplot(data=d, aes(x = interaction(year, growth), y=sells, fill = state)) + 
  geom_col(position="dodge") +
  scale_x_discrete(labels = unique(interaction(d$year, factor(d$growth), sep = "\n")))+
  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")) + 
  guides(fill = guide_legend(nrow = 1)) +
  labs(x = expression(Year~growth), y = "Sells")

Created on 2020-07-10 by the пакет реплекс (v0.3.0)

2 голосов
/ 10 июля 2020

Насколько мне известно, в 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")

enter image description here

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")

enter image description here

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")

введите описание изображения здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...