Reputation: 51
I have a dataset with two variables: 1) Country; 2) Coalition government or not over time (binary).
I want to use ggplot to plot a bar plot in which I have country on the X-axis and the percentage of years in which the country had a coalition government (Y=1). Each of the countries should sum to 100 pct. leading to them having the same size.
It is basically the same plot which is asked for in this question (Create stacked barplot where each stack is scaled to sum to 100%), except that I have only two outcomes (coalition government or not) and not five.
Although I follow the instructions in the answer to the question, I get the attached unsuccesful plot, using this code:
ggplot(data,aes(x = countryname, y = alliance,fill = alliance)) +
geom_bar(position = "fill",stat = "identity") +
scale_y_discrete(labels = percent_format())
I don't know what I am doing wrong, and I have tried so many different things now. Can anyone help me?
Upvotes: 1
Views: 3969
Reputation: 2289
I'll try and answer by generating some random data to match your description. Hopefully you can re-purpose this example for your needs.
# Sample data set
year <- 1990:2016
n <- length(year)
country <- rep(c("US", "Canada", "England", "France", "Germany"), each = n)
govt <- sample(c(1, 0), size = length(country), replace = T)
df <- data.frame(country, year = rep(year, times = 5), govt)
head(df)
# Create summary
library(ggplot2)
library(dplyr)
library(reshape2)
df.plot <- df %>%
group_by(country) %>%
summarize(coalition = sum(govt)/n(),
non.coalition = 1-coalition)
# Check
rowSums(df.plot[,-1])
# Now plot
df.plot %>%
melt() %>%
ggplot(aes(x = country, y = value, fill = variable)) + geom_bar(stat = "identity", position = "stack") +
xlab("Country") +
ylab("Percent Coalition / Non Coalition") +
scale_fill_discrete(guide = guide_legend(title = "Type of Govt."))
Upvotes: 2