David Marin
David Marin

Reputation: 1

Side by side barplot in R with ggplot

I used the next code in order to get a barplot representing the relative frequencies of my dataset.

ggplot(Votantes_Col,aes(x=Voto)) +
  geom_bar(aes(y = (..count..)/sum(..count..))) +
  scale_y_continuous(labels=scales::percent) +
  ylab("Frecuencias relativas")

Plot 1

Until here everything its ok. But now i need to add in the same chart another barplot like this one.

Plot 2

The final chart should compare the frequencies of YES/NO on both countries. The problem is that the two datasets have different length so i cant bind them in one data frame. Thanks for your help.

Upvotes: 0

Views: 81

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174476

It sounds like you want data from both countries on a single plot.

You are only plotting a single variable, so it is easy to join the data from the two countries together. Let us recreate your plots with some sample data:

Plot 1:

library(ggplot2)

Votantes_Col <- 
  data.frame(Voto = rep(c("No", "Si"), c(22, 79)))

ggplot(Votantes_Col, aes(x = Voto)) +
  geom_bar(aes(y = (..count..)/sum(..count..))) +
  scale_y_continuous(labels=scales::percent) +
  ylab("Frecuencias relativas")

Plot 2:

Otros_Votantes_Col <- 
  data.frame(Voto = factor(rep(c("Si", "No", "NS/NR"), c(65, 33, 1)),
                           levels = c("Si", "No", "NS/NR")))

ggplot(Otros_Votantes_Col, aes(x = Voto)) +
  geom_bar(aes(y = (..count..)/sum(..count..))) +
  scale_y_continuous(labels=scales::percent) +
  ylab("Frecuencias relativas")

Now all we need to do is take the Voto column from each data frame, and concatenate them together (ensuring they are first characters rather than factors). We put this column in a new data frame with a second column labelling which country they came from:

df <- data.frame(Voto = c(as.character(Votantes_Col$Voto), 
                          as.character(Otros_Votantes_Col$Voto)),
                 Pais = rep(c("Pais_1", "Pais_2"), 
                            c(nrow(Votantes_Col), nrow(Otros_Votantes_Col))))

Now we simply use this to create our new plot. We will use the column Pais as the fill colour for our bars:

Plot 3:

ggplot(df, aes(x = Voto, fill = Pais)) +
  geom_bar(aes(y = (..count..)/sum(..count..)), position = position_dodge()) +
  scale_y_continuous(labels=scales::percent) +
  ylab("Frecuencias relativas")

Created on 2020-09-08 by the reprex package (v0.3.0)

Upvotes: 3

Related Questions