繁体   English   中英

在R中重新排序ggplot2 barplot

[英]Reorder ggplot2 barplot in R

我有dat其中包含产品的功能和景气指数。

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)

而且,我用下面的代码用ggplot2作了图

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

即使我使用了reorder ,我也只有这张照片。

在此处输入图片说明

尽管我喜欢整体服装,但我希望这些功能能够按顺序使用,例如decreasing = T并仅展示具有最高或最低人气得分的Top4功能的Top3产品POLAR

在此处输入图片说明

就像上面的图片一样,我想订购功能,但只是针对每种产品展示一些功能。

您可以这样做:

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))

给出:
在此处输入图片说明

#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))

给出:
在此处输入图片说明

并归功于Axeman出色的功能来重命名标签。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM