首页 > 解决方案 > 在使用 ggplot2 打印为条形图之前按 R 中的数字排序

问题描述

我有这张图表:

在此处输入图像描述

我想像这样从低到高 WidthGroup 订购它:

在此处输入图像描述

我的输入是图片的 ID、宽度和高度。我首先遍历所有行并将它们添加到正确的组中。然后我将其绘制为条形图。我的问题是我想更改条形图的顺序,使其从低到高。

这是我的代码:

# Library
library(ggplot2)
library(tidyverse)

# 1. Read data
df = read.csv2(text = "ID;Width;Height
1;255;298
2;600;900
3;333;459
4;333;459
5;800;574
6;512;768
7;768;1024
8;768;1024
9;800;574
10;512;768
11;640;1136
12;1200;1600
13;255;298
14;600;900
15;600;900
16;255;298
17;512;768
18;600;900
19;255;298
20;600;900
21;768;1024
22;255;298
23;640;1136
24;640;1136
25;333;459
26;255;340
27;1200;1600
28;640;1136
29;255;298
30;255;298
31;180;180
32;920;920
33;950;950")

# Count
number_of_rows <- nrow(df)
print(paste0("Number of rows: ", number_of_rows, sep=''))

# loop trough rows and add to new data frame
df_dimension <- data.frame(matrix(ncol = 1, nrow = 0))
names <- c("WidthGroup")
colnames(df_dimension) <- names

for(x in 1:number_of_rows) {
  width <- df[x, "Width"]
  height <- df[x, "Height"]
  
  if(!is.null(width)){
    if(width < 299){
      df_dimension[nrow(df_dimension) + 1,] = c("0-299")
    }
    else if(width > 300 && width < 599){
      df_dimension[nrow(df_dimension) + 1,] = c("300-599")
    }
    else if(width > 600 && width < 899){
      df_dimension[nrow(df_dimension) + 1,] = c("600-899")
    }
    else if(width > 900 && width < 1199){
      df_dimension[nrow(df_dimension) + 1,] = c("900-1199")
    }
    else if(width > 1200 && width < 1399){
      df_dimension[nrow(df_dimension) + 1,] = c("1200-1399")
    }
    else{
      df_dimension[nrow(df_dimension) + 1,] = c("1400->")
    }
  }
  else{
    print("Warning empty")
  }
} # // for rows

# Count and arrange data
df_dimension <- as.data.frame(table(df_dimension))
colnames(df_dimension)[which(names(df_dimension) == "df_dimension")] <- "WidthGroup" # Rename column
df_dimension

# Plot bar chart
ggplot(df_dimension, aes(x = WidthGroup, y = Freq)) + 
        geom_bar(stat = "identity") + 
        theme_classic() + 
        coord_flip() +
        ggtitle("Pictures within given Width") +
        xlab("Width Group") + 
        ylab("Frequency") +
        geom_text(aes(label = Freq), hjust = -0.5)


标签: rggplot2

解决方案


尝试创建一维列:

#auxiliar column
df_dimension$aux <- as.numeric(unlist(strsplit(as.character(df_dimension$WidthGroup), '-')))[seq(1,2*nrow(df_dimension),by = 2)]
df_dimension <- df_dimension[order(df_dimension$aux),]

# Plot bar chart
ggplot(df_dimension, aes(x = reorder(WidthGroup,-aux), y = Freq,)) + 
  geom_bar(stat = "identity") + 
  theme_classic() + 
  coord_flip() +
  ggtitle("Pictures within given Width") +
  xlab("Width Group") + 
  ylab("Frequency") +
  geom_text(aes(label = Freq), hjust = -0.5)

推荐阅读