在R中重新排序ggplot2 barplot

时间:2017-02-08 10:29:29

标签: r

我有gfortran main.f90 cic.f90 -o main.so ,其中包含产品'特征和情感分数。

dat

而且,我用ggplot2制作了一个情节,下面的代码是

TAL = c('Samsung','Apple','LG','Sonic','Motorola','Samsung','Apple','LG','Sonic','Motorola','Samsung','Apple','LG','Sonic','Motorola','Samsung','Apple','LG','Sonic','Motorola','Samsung','Apple','LG','Sonic','Motorola','Samsung','Apple','LG','Samsung','Apple','LG','Samsung','Apple','LG','Samsung','Apple')
FEL = c('color','price','name','brand','sound','technology','general','height','width','color','price','name','brand','sound','technology','general','height','width','color','price','name','brand','sound','technology','general','height','width','color','price','name','brand','sound','technology','general','height','width')
POLAR = c(10,-5,5,-8,6,3,5,10,-5,5,-8,6,3,5,10,-5,5,-8,6,3,5,10,-5,5,-8,6,3,5,10,-5,5,-8,6,3,5,10)
dat = data.frame(TAL,FEL,POLAR)

即使我使用sentim <- ggplot(dat, aes(x=reorder(FEL,-POLAR), y=POLAR, fill= POLAR > 0)) + geom_bar(stat = "identity", show.legend = F)+ xlab("Feature") + ylab("Sentiment score") + facet_grid(. ~ TAL, scales = "free") + theme(panel.background = element_blank(), plot.background = element_blank(), panel.grid.major.x = element_line(size=0.1, colour = 'grey', linetype=3), panel.grid.minor.x = element_line(size=0.1, colour = 'grey', linetype=3), panel.spacing = unit(1, 'lines'), axis.line = element_line(size=0.6, colour = 'black'), axis.text = element_text(colour = 'black'), axis.ticks = element_line(colour = 'black')) sentim ,我也只是有了这张照片。

enter image description here

虽然我喜欢整体服装,但我希望这些功能可以使用像reorder这样的东西,只是为了展示具有最高或最低情绪分数的Top4功能的Top3产品 - decreasing = T

enter image description here

如上图所示,我想订购功能,但只是为每种产品展示一些功能。

1 个答案:

答案 0 :(得分:2)

你可以这样做:

dat$temp_var <- paste(dat$TAL, dat$FEL) #creates a secondary variable
library(dplyr)
#get the sum for each TAL-FEL group of POLAR and sort by decreasing order
dat=dat%>%group_by(TAL,FEL)%>%mutate(tot=sum(POLAR))%>%arrange(tot)

ggplot(dat, aes(reorder(temp_var, tot), POLAR,fill= POLAR > 0))+
  geom_bar(stat = "identity", show.legend = F)+
  facet_wrap(~TAL,scales="free_x")+
   scale_x_discrete(labels = setNames(as.character(dat$FEL), dat$temp_var))

给出:
enter image description here

#If you want to focus on what's bad and need work you can filter out what you considering uninteresting, here if total of POLAR>5.
dat_bad=dat%>%group_by(TAL,FEL)%>%mutate(tot=sum(POLAR))%>%arrange(tot)%>%filter(tot<5)

ggplot(dat_bad, aes(reorder(temp_var, tot), POLAR,fill= POLAR > 0))+
  geom_bar(stat = "identity", show.legend = F)+
  facet_wrap(~TAL,scales="free_x")+
  scale_x_discrete(labels = setNames(as.character(dat$FEL), dat$temp_var))

给出:
enter image description here

并且感谢Axeman提供了很好的function来重命名标签。