1

I am trying to make a barplot that is not stackable and so far I was able to go quite far.

Since I have found out that ggplot plots the data.frame as is, without ordering I have ordered my data.frame before feeding it to ggplot. Where I ordered it based on word occurences

Both<-Both[order(Both$occurence,decreasing=TRUE),]

The structure looks like now as

 str(Both)
'data.frame':   82 obs. of  3 variables:
 $ word     : Factor w/ 6382 levels "a","abcc","abda",..: 1595 1994 
 $ occurence: int  4171 3004 2145 1821 1798 1745 1614 1539 1531 1349 ...
 $ sentiment: num  0 0 0 0 0 0 0 0 0 0 ...

Variable

> Both
           word occurence sentiment
**19**            i      4171         0
**12**            m      3004         0
**34**         true      2145         0
**36**      kubelet      1821         1
**18**       normal      1798         1

Plot

ggplot(data=Both,aes(x=word,y=occurence,factor(sentiment),fill=factor(sentiment)))+
coord_flip()+geom_bar(stat="identity",position="identity")
## remove identity to make them stackable. one after the other

but it looks like that ggplot orders my xlabel based on the alphabetical order of the words in other terms the number that is visible in my Both structure and I highlight with ** **.

Why my ordering is not enough? Why ggplot still plots the labels alphabetically?

Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
Alex
  • 25
  • 3
  • that highly upvoted absolute duplicate is hit #1 on google for `ggplot2 order barplot` – hrbrmstr Nov 15 '18 at 13:14
  • they discuss on factor ordering which based on my understanding is not similar to the data.frame. I am still new to R But I searched for those solutions and I could not apply any of these suggestions I got. – Alex Nov 15 '18 at 15:41

1 Answers1

0

You need to re-order the factor levels from your word column. The order of the levels of that factor will be used to order the x axis.

Use the function factor for example.

require(ggplot2)

df <- data.frame(word = as.factor(c('a','b','c')),
          cnt = c(10,20,15))

ggplot(df, aes(x = word, y = cnt)) +
  geom_bar(stat = 'identity')

df$word <- factor(df$word, levels = c('b','c','a'))

ggplot(df, aes(x = word, y = cnt)) +
  geom_bar(stat = 'identity')
Wietze314
  • 5,942
  • 2
  • 21
  • 40