Skip to content

ggplot2 barplot in decreasing frequency

3 messages · Morten, Ista Zahn, Dennis Murphy

#
Hi all,

I have a large data frame and would like to make a barplot of a categorical
variable with the bars sorted in order of decreasing frequency.

# Example:
v1 = c(1.2, 1.4, 0.9, 1.0, 1.1, 1.0)
v2 = c("aa", "cc", "bb", "bb", "cc", "bb")
v3 = c(8, 10, 11, 9, 9, 10)
df = data.frame(v1=v1, v2=v2, v3=v3)

# How can I tell ggplot to sort the bars?
# First bar = "bb" (3), second bar "cc" (2) and third bar "aa" (1)

p = gplot(df)
p + aes(v2) + geom_bar()


Thank you,

Morten
#
Hi Morten
Just order the factor the way you want before plotting:

df$v2 <- factor(df$v2, levels=c("bb", "cc", "aa"))

p = ggplot(df)
p + aes(v2) + geom_bar()


Best,
Ista
On Wed, Oct 6, 2010 at 5:09 AM, Morten <Morten.Lindberg at siv.no> wrote: