堆栈顺序不正确,标识为geom_bar

时间:2019-02-28 19:16:46

标签: r ggplot2

我使用dplyr过滤了一个数据集,这导致了下面的标题。我要创建一个堆叠的条形图,其中包含功能类型及其功能级别。我希望条形图从最大频率到最小频率排序。

使用下面的代码,输出的图将前两个值反转。这是因为“位置”只有两个功能级别,而其余的只有三个功能级别吗?即便如此,最高的总体频率还是96,并且属于“距离”级别。

理想情况下,我希望做最少的“强行强制”操作,以使代码能够正常工作,因为我正在使用的实际数据具有10多种功能,某些功能只有一个功能级别。

# A tibble: 11 x 3
# Groups:   Type.of.Feature [?]
   Type.of.Feature Capability.Category  Freq
   <fct>           <chr>               <int>
 1 Diameter        <1                     75
 2 Diameter        >1.33                   5
 3 Diameter        1-1.33                 13
 4 Distance        <1                     96
 5 Distance        >1.33                   5
 6 Distance        1-1.33                  6
 7 Position        <1                     90
 8 Position        >1.33                   4
 9 Radius          <1                      7
10 Radius          >1.33                   1
11 Radius          1-1.33                  2


ggplot(freq, aes(x=reorder(Type.of.Feature, -Freq), y=Freq, fill=Capability.Category)) +
   geom_bar(stat="identity", position="stack")

enter image description here

1 个答案:

答案 0 :(得分:0)

请按照以下步骤订购吧台

#Import Data
file1<- readxl::read_excel(file.choose())

#Import Required Libraries
library(ggplot2)
library(dplyr)

#Split Dataframe into list based on the Type.of.Feature factor
factor_list <-split.data.frame(file1, f= file1$Type.of.Feature)


#Create new column with frequency sum for each of the level of factor above
for( lnam in names(factor_list)){
  factor_list[[lnam]]["group_sum"]<- sum(factor_list[[lnam]]["Freq"])
}

#Get back the data into dataframe
file1<- rbind_list(factor_list)

#Use newly created group frequency to order your bars
ggplot(file1, aes(x=reorder(Type.of.Feature, -group_sum), y=Freq, fill=Capability.Category)) +
  geom_bar(stat="identity", position="stack")
相关问题