-1

I have a sorted frame, but when I use ggplot to plot it, the words are not appear in the correct order as they are in the dataframe. The code is the following:

library(ggplot2)

df<-data.frame(word=c("play","win","offer","http","right","internet"),frequency=c(321,355,123,899,564,433),type=c("nonspam","nonspam","spam","spam","spam","spam"))
df=df[order(df$type, df$frequency, decreasing = TRUE),]

ggplot(df, aes(x=frequency, y=word)) +
  geom_segment(aes(yend=word), xend=0, color='grey50') +
  geom_point(size=3, aes(color=type)) + 
  scale_color_brewer(palette='Set1', limits=c('Spam', 'non-Spam'), guide=F) +
  theme_bw() +
  theme(panel.grid.major.y = element_blank()) +
  facet_grid(type ~ ., scales='free_y', space='free_y')
Heikki
  • 2,214
  • 19
  • 34
toumperlekis
  • 39
  • 1
  • 9

2 Answers2

0

You have to order the levels of the variable. It doesn't matter the order in your dataframe when you plot something with ggplot (it uses the level order). What order do you want? By name? Or by frequency?

Daniel Gimenez
  • 551
  • 3
  • 6
  • by frequency but for each type. Namely, the first line will be 899 and the last 123 for the spam messages. And then 355 and 321 for the non spam messages. But I tried to reorder and It failed, can you please tell me how to do it? – toumperlekis Nov 23 '17 at 11:59
0

As mentioned, you have to set factors:

df <- data.frame(word=c("play","win","offer","http","right","internet"),
                 frequency=c(321,355,123,899,564,433),
                 type=c("nonspam","nonspam","spam","spam","spam","spam"))  

your_order <- order(df$frequency)
df$word <- factor(df$word, levels = df$word[your_order])

ggplot(df, aes(x=frequency, y=word)) +
  geom_segment(aes(yend=word), xend=0, color='grey50') +
  geom_point(size=3, aes(color=type)) + 
  scale_color_brewer(palette='Set1', limits=c('Spam', 'non-Spam'), guide=F) +
  theme_bw() +
  theme(panel.grid.major.y = element_blank()) +
  facet_grid(type ~ ., scales='free_y', space='free_y')

With these commands your plot should appear as expected.

enter image description here

J_F
  • 9,956
  • 2
  • 31
  • 55