簡體   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