ggplot和收集不同的价值水平和group_by

时间:2018-05-14 11:11:39

标签: r ggplot2

我想要一个使用数据集的不同字符值的频率的条形图。我有4个不同级别的问题,需要使用facet_wrap进行绘图

行为:即使使用group_by ggplot也会使用所有字符值来绘制导致无意图的频率。

enter image description here 预期行为:4个不同的方面及其相对水平。

  `difficulty_pre_How was the pace of the class?` `difficulty_pre_How muc… `difficulty_pre_How m… `difficulty_pre_Conside…
  <chr>                                           <chr>                    <chr>                  <chr>                   
1 About right                                     51-75%                   1-25%                  About right             
2 Too slow                                        51-75%                   91-100%                Very easy               
3 Too fast                                        51-75%                   76-90%                 About right             
4 About right                                     1-25%                    91-100%                About right             
5 Fast                                            51-75%                   26-50%                 About right             

我的代码:

data %>% 
 na.omit() %>% 
  gather() %>%
  mutate(key = str_sub(key, start = 16)) %>% #need to cut unecessary letter from key 
  group_by(key,value) %>%
  ggplot(aes(x = value)) +
  geom_bar(aes(y = (..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..])) +
  scale_y_continuous(labels=percent,limits = c(-0, 1)) +
  scale_x_discrete(drop=FALSE) +
  ylab("Relative Frequencies (%)") +
  xlab("") +
  facet_wrap(~ key) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 0.9))+
  theme(strip.text = element_text(size=6))

1 个答案:

答案 0 :(得分:0)

决议:根据GGamba的建议,在facet_wrap()内添加data %>% na.omit() %>% gather() %>% mutate(key = str_sub(key, start = 16)) %>% #need to cut unecessary letter from key group_by(key,value) %>% ggplot(aes(x = value)) + geom_bar(aes(y = (..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..])) + scale_y_continuous(labels=percent,limits = c(-0, 1)) + scale_x_discrete(drop=FALSE) + ylab("Relative Frequencies (%)") + xlab("") + facet_wrap(~ key,scale='free_x') + theme_bw() + theme(axis.text.x = element_text(angle = 90, hjust = 0.9))+ theme(strip.text = element_text(size=6))

{{1}}