2017-02-06 8 views
-1

Ich habe den folgenden Code:Sortieren von Daten in Graph in R

library(ggplot2) 
ggplot(data = diamonds, aes(x = cut)) + 
    geom_bar() 

mit this result.

Ich möchte das Diagramm auf die Anzahl absteigend sortieren.

+0

Eine Möglichkeit ist, Daten zu sortieren, bevor sie zu dem Graphen hinzugefügt. Teilen Sie Ihren R-Code bitte mit Beispieldaten. –

Antwort

1

Es gibt mehrere Möglichkeiten, dies zu tun (es ist wahrscheinlich nur durch die Verwendung von Optionen innerhalb von ggplot möglich). Aber eine Art und Weise dplyr Bibliothek zunächst die Daten zusammenfassen und dann ggplot verwenden zu zeichnen das Balkendiagramm könnte wie folgt aussehen:

# load the ggplot library 
library(ggplot2) 
# load the dplyr library 
library(dplyr) 
# load the diamonds dataset 
data(diamonds) 

# using dplyr: 
# take a dimonds dataset 
newData <- diamonds %>% 
     # group it by cut column 
     group_by(cut) %>% 
     # count number of observations of each type 
     summarise(count = n()) 

# change levels of the cut variable 
# you tell R to order the cut variable according to number of observations (i.e. count variable) 
newData$cut <- factor(newData$cut, levels = newData$cut[order(newData$count, decreasing = TRUE)]) 

# plot the ggplot 
ggplot(data = newData, aes(x = cut, y = count)) + 
     geom_bar(stat = "identity") 
+0

Vielen Dank lieber @PeterSmith –