Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Wrong order of y values in ggplot barplot

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading