0
votes

I need two graphs for below data set.

1) First just one bar shows the NonProm,Promo1,Promo2 with different colors to compare the sales

2) Second one with three different bars for each Promotion again for comparison

data = data.frame(
  Promotion =c('NonProm','Promo1','Promo2'),
  Sales = c(1616408,95219,92365))

For the second one I did try but I got error message

p<-ggplot(data=data, aes(x=Promotion , y=Sales)) +
   geom_bar(width=1) +
   scale_y_continuous(expand = c(0,0))  
p

"Don't know how to automatically pick scale for object of type function. Defaulting to continuous. Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 0, 5 "

Thank you.

2
You need stat=identity in the geom_bar() . Try the following, ggplot(data=data1, aes(x=Promotion , y=Sales)) + geom_bar(stat = "identity", width = 1) + scale_y_continuous(expand = c(0,0))mnm

2 Answers

0
votes

I'm not sure what you mean by #1 but please try this. I did this in R Studio. I found sample code here: http://www.sthda.com/english/wiki/ggplot2-barplots-quick-start-guide-r-software-and-data-visualization

data = data.frame(
  Promotion =c('NonProm','Promo1','Promo2'),
  Sales = c(1616408,95219,92365))
data

library(ggplot2)

# Change barplot fill colors by groups
p<-ggplot(data, aes(x=Promotion, y=Sales, fill=Promotion)) +
  geom_bar(stat="identity")+theme_minimal()
p
0
votes

For issue #1, to get a stacked bar chart, you need values to have the same x-position. In a larger dataset, you might have an x-value for dates at which sales were made, sales people, etc. Since you don't have another column like this in your data, I just put a dummy value inside the aes to set x.

In more recent versions of ggplot2, geom_bar assumes you want to plot counts of categories, not the values themselves, so to plot actual values, you can use either geom_bar(stat = "identity") or geom_col(). To stack bars, set position = "stack".

For issue #2, I'm not getting your error with your code, but instead got:

Error: stat_count() must not be used with a y aesthetic.

This is because geom_bar assumes it will be counting observations, which conflicts with supplying a y aesthetic.

Note that I set a fill and color to the bars because I kept your width = 1. This makes it pretty impossible to tell one bar from the next.

library(tidyverse)

data <- data.frame(
  Promotion =c('NonProm','Promo1','Promo2'),
  Sales = c(1616408,95219,92365))

ggplot(data, aes(x = "Promotions", y = Sales, fill = Promotion)) +
  geom_col(position = "stack")

ggplot(data, aes(x = Promotion, y = Sales)) +
  geom_col(width = 1, fill = "white", color = "black") +
  scale_y_continuous(expand = c(0, 0))

Created on 2018-05-20 by the reprex package (v0.2.0).