2017-10-21 92 views
0

我想ra-安排我的ggplot条形图的条形 - 在这里有很多类似的条目在stackoverflow上(例如here)。只使用一个变量(无值或排名)在ggplot2条形图中重排条形图?

但是,我的问题是:你可以通过告诉ggplot不要按标签按字母顺序进行排序,而只用一个变量(用于条形图的变量)进行此操作,但可以通过将相同标签的计数值作为值出于兴趣。

就我而言,我有一个调查数据,说明哪个政党在某个问题领域中最能胜任某个问题的问题。

respondent-id competence 
1    "Party A" 
2    "Party A" 
3    "Party B" 
4    "Party B" 
5    "Party B" 
6    "Party C" 

什么ggplot现在会做的是与第二高的第一(甲方)的条形图,最高的第二方(乙方)与去年最低(丙方)。但是,我该如何告诉ggplot考虑计数(2:3:1 - >先放置B方)?

我试过几种方法的建议here,但这并没有解决这个问题:他们大多包括一个位置变量,它会告诉ggplot“指定乙方第一名”。我也试图简单地通过“能力”来reorder(),但没有成功。最后,我可以为各方分配不同的前缀(“1_party_B”,“2 _...”),但那将是非常繁琐的工作。

ggplot(MyData, aes(x=competence,y=(..count..))) + geom_bar() 

另外,我有一个NA-酒吧在我的条形图和MyData[,c("competence")]似乎没有这样的伎俩。但这是另一回事。

在此先感谢!

+0

首先,你必须创建具有计数另一个表,然后绘制出来。使用'table()'为每个参与者准备计数表 –

回答

1
library(ggplot2) 

df 
# resp comp 
# 1 1 Party A 
# 2 2 Party A 
# 3 3 Party B 
# 4 4 Party B 
# 5 5 Party B 
# 6 6 Party C 

df1 <- data.frame(table(df$comp)) 
df1 
#  Var1 Freq 
# 1 Party A 2 
# 2 Party B 3 
# 3 Party C 1 

手动安排使用水平factor()

df1$Var1 <- factor(df1$Var1, c("Party B", "Party C", "Party A")) 
df1 
#  Var1 Freq 
# 2 Party B 3 
# 3 Party C 1 
# 1 Party A 2 


ggplot(df1, aes(x = Var1, y = Freq)) + geom_bar(stat = "identity") 

enter image description here

频率党的递减顺序

df1 <- data.frame(table(df$comp)) 
df1 
#  Var1 Freq 
# 1 Party A 2 
# 2 Party B 3 
# 3 Party C 1 

df1 <- df1[order(df1$Freq, decreasing=TRUE),] 
df1 
#  Var1 Freq 
# 2 Party B 3 
# 1 Party A 2 
# 3 Party C 1 

ggplot(df1, aes(x = Var1, y = Freq)) + geom_bar(stat = "identity") 

enter image description here

0

取决于如果你想有一个从大到小的顺序上,你可以做到这一点简单地用dplyrreorder

library(dplyr) 
library(ggplot2) 

count(df, competence) %>% 
     ggplot(aes(x = reorder(competence, -n), y = n)) + 
     geom_col() 

enter image description here