Home > Enterprise >  Barplot with paneldata
Barplot with paneldata

Time:12-20

I'm struggling quiet a lot to make a barplot showing me, how many observations in each category of voted

The thing is. I have a "voted" variable in my panel dataframe, numeric which is telling me, which party one voted for in 2012 and 2014.

Here is a reproducible example

id <- c('1','1','1','2','2','2','3','3','3')
wave <- c(2012, 2013, 2014, 2012, 2013, 2014, 2012, 2013, 2014)
voted <- c(1, NA, 4, 1, NA, 2, 2, NA, 4)
mydata <- data.frame(id, wave, voted)

There has only been election in 2012 and 2014 - and therefore the NA's. Each number stands for a name of the party.

I want to show in a barplot how many respondents voted for party 1, 2, 4...

I've tried the following:

ggplot(mydata, aes(x = as.factor(voted), y = year, fill = year))  
  geom_bar(stat = "identity", position = "dodge")

However as you might see, it looks really weird.

enter image description here

CodePudding user response:

This is an illustration of applying the issues I identified in the comment above:

In a barplot the y value is the height of the bar which I think is "voted" in your request and the x value is the categories, probably "id" and the subcategories probably "year". I don't think you want to make the y value a factor. Furthermore "year" is not a column name and you are missing a parenthesis in the ggplot call. (You should have gotten and error with that code. –

ggplot(mydata, aes(x = id, y = voted, fill = factor(wave)))  
    geom_bar(stat = "identity", position = "dodge")
#Warning message:
#Removed 3 rows containing missing values (geom_bar). 

enter image description here

  • Related