4

In R ggplot, I need to make a barplot where bars are grouped together based on a factor called "Mode". There should be spacing between each group of bars.

I see in SO that different versions of this problem have come up previously, but the answers provided don't seem to apply to my case.

Here is my data.frame:

> df_mainContributors
                  Top_contributor Eigvec_value Mode
1         Indonesia Cassava dried    0.3489285    2
2  China, mainland Sweet potatoes   -0.3280290    2
3           China, mainland Maize   -0.2848236    2
4              Indonesia Potatoes   -0.2749160    2
5             Thailand Cottonseed   -0.3844600    3
6               Thailand Soybeans    0.3531400    3
7                 Indonesia Maize    0.3308546    3
8          China, mainland Millet   -0.2620598    3
9        China, mainland Potatoes   -0.3883072    4
10                  Thailand Rice    0.3108829    4
11   China, mainland Oil, soybean    0.2783780    4
12        Thailand Sweet potatoes    0.2754683    4

Here is my code, where I have tried to implement the answers given here and here.

  df_plot <- df_mainContributors
  df_plot$Mode <- as.factor(df_plot$Mode)
  df_plot$Top_contributor <- factor(df_plot$Top_contributor, levels = unique(df_plot$Top_contributor))
  dodge <- position_dodge(width = 0.9)
  ggplot(df_plot, aes(x = Top_contributor, y = Eigvec_value, fill = Mode)) +
    geom_bar(color = "black", stat = "identity", position = dodge, width = 0.9) +
    theme(axis.text.x = element_text(angle = 60, hjust = 1))

And here is the no-space-between-groups-having graphic that results:

enter image description here

ben
  • 787
  • 3
  • 16
  • 32
  • 3
    Possible duplicate of [Specific spaces between bars in a barplot - ggplot2 - R](https://stackoverflow.com/questions/30100500/specific-spaces-between-bars-in-a-barplot-ggplot2-r) – bouncyball Jul 24 '18 at 16:22

1 Answers1

3

Try this (I added scale_x_discrete stuff to your ggplot, did not want to mess with the contents of the data frame itself)

  ggplot(df_plot, aes(x = Top_contributor, y = Eigvec_value, fill = Mode)) +
  geom_bar(color = "black", stat = "identity", position = dodge, width = 0.9) +
  scale_x_discrete(limits = c(levels(df_plot$Top_contributor)[1:4],
                              "ABC",
                              levels(df_plot$Top_contributor)[5:8],
                              "DEF",
                              levels(df_plot$Top_contributor)[9:12]),
                   labels = c("ABC" = "",
                              "DEF" = "")) +
  theme(axis.text.x = element_text(angle = 60, hjust = 1))

Result (note I didn't put in all the decimal places for your Eigens):enter image description here

Joy
  • 769
  • 6
  • 24