Wrong order of y values in ggplot barplot

Advertisements

I’ve got 3 groups, each one showing the number of sales for two types of clients (historical and tele-rehab).
I’m trying to plot the sales in the order I defined them:

In the BI gain group:

First sale is historical, black colour = 30

Second sale is tele-rehab. white colour = 20

In the BI efficiency:

First sale is historical, black colur = 49

Second sale is tele-rehab, white colur = 47

In the BI effectiveness:

First sale is historical, black colour =58

Second sale is tele-rehab, white colur=60

When I try to plot it ggplot changes the order of the sales

ibrary(ggplot2)
df <- data.frame(stadium=c('BI gain', 'BI efficiency', 'BI effectiveness'),
                 food=c('historical','tele-rehab', 'historical','tele-rehab', 'historical','tele-rehab'),
                 sales=c(30.0, 20.0, 49.0, 47.0, 58.0, 60.0))
df$stadium <- as.factor(df$stadium)
df$stadium <- factor(df$stadium, levels=unique(df$stadium))

df$sales<-as.numeric(as.character(df$sales))


ggplot(df, aes(fill=food, y=sales, x=stadium)) +
  geom_bar(position='dodge', stat='identity',colour="black")+
  scale_fill_manual ('Where', values = c("black","white"))

I defined the sales as numeric, but ggplot changes the order.

>Solution :

The problem is how you defined your dateframe. You listed the stadiums only once each and thus R does autofill then. Just list all the possible stadiums in your dataframe. See code below:

library(ggplot2)
df <- data.frame(stadium=c('BI gain', 'BI gain', 
                           'BI efficiency', 'BI efficiency', 
                           'BI effectiveness', 'BI effectiveness'),
                 food=c('historical','tele-rehab', 
                        'historical','tele-rehab', 
                        'historical','tele-rehab'),
                 sales=c(30.0, 20.0, 
                         49.0, 47.0, 
                         58.0, 60.0))
df$stadium <- as.factor(df$stadium)
df$stadium <- factor(df$stadium, levels=unique(df$stadium))

df$sales<-as.numeric(as.character(df$sales))


ggplot(df, aes(fill=food, y=sales, x=stadium)) +
  geom_bar(position='dodge', stat='identity',colour="black")+
  scale_fill_manual ('Where', values = c("black","white"))

Leave a ReplyCancel reply