带面板数据的条形图
Barplot with paneldata
我一直在努力安静地制作一个条形图,向我展示 voted
的每个类别中有多少观察值
事情是这样的。我的面板数据框中有一个“投票”变量,数字告诉我,哪个政党在 2012 年和 2014 年投票给了哪个政党。
这是一个可重现的例子
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)
仅在 2012 年和 2014 年举行过选举 - 因此是国民议会。每个数字代表党的名称。
我想在条形图中显示有多少受访者投票给政党 1、2、4...
我试过以下方法:
ggplot(mydata, aes(x = as.factor(voted), y = year, fill = year)) +
geom_bar(stat = "identity", position = "dodge")
然而,如您所见,它看起来真的很奇怪。
ggplot
我对这样的东西更感兴趣:
How it should look
有人有什么建议吗?提前致谢!
这是应用我在上面评论中确定的问题的说明:
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).
您在找这样的东西吗?
library(dplyr)
library(ggplot2)
mydata %>%
group_by(wave) %>%
count(voted) %>%
ggplot(aes(x=factor(voted), n, fill=factor(wave)))+
geom_col(position = position_dodge())
我一直在努力安静地制作一个条形图,向我展示 voted
事情是这样的。我的面板数据框中有一个“投票”变量,数字告诉我,哪个政党在 2012 年和 2014 年投票给了哪个政党。
这是一个可重现的例子
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)
仅在 2012 年和 2014 年举行过选举 - 因此是国民议会。每个数字代表党的名称。
我想在条形图中显示有多少受访者投票给政党 1、2、4...
我试过以下方法:
ggplot(mydata, aes(x = as.factor(voted), y = year, fill = year)) +
geom_bar(stat = "identity", position = "dodge")
然而,如您所见,它看起来真的很奇怪。
ggplot
我对这样的东西更感兴趣:
How it should look
有人有什么建议吗?提前致谢!
这是应用我在上面评论中确定的问题的说明:
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).
您在找这样的东西吗?
library(dplyr)
library(ggplot2)
mydata %>%
group_by(wave) %>%
count(voted) %>%
ggplot(aes(x=factor(voted), n, fill=factor(wave)))+
geom_col(position = position_dodge())