2

I have this data frame called data:

head(data)

     date         total_sold purchasability visibility
81 2014-05-01          3              3          3
82 2014-05-02          2              2          3
83 2014-05-03          1              2          3
84 2014-05-04          1              3          3
85 2014-05-05          3              2          3
86 2014-05-06          0              0          3

And I would like to do a bar chart with x = date and y = total_sold with a color depending on the purchasability. I this ggplot2 to do that :

bar <- ggplot(data = data, aes(x = date, fill=as.factor(purchasability),y = total_sold)) + geom_bar(stat = 'identity')

The output is very nice but the problem is that where total_sold = 0 there is not chart and thus no way to know the purchasability. Is it possible to still display a bar (maybe from 0.5 to -0.5) when total_sold = 0 ?

Thanks

user2741700
  • 881
  • 3
  • 11
  • 21

2 Answers2

11

You can just use geom bar, please look this code

df <- data.frame(time = factor(c("Lunch","Dinner","breakfast","test"), levels=c("Lunch","Dinner","breakfast","test")),
                  total_bill = c(14.89, 0,0.5,-0.5))
# Add a black outline
ggplot(data=df, aes(x=time, y=total_bill, fill=time)) + geom_bar(colour="black", stat="identity")

enter image description here

rischan
  • 1,553
  • 13
  • 19
0

I'm not sure there's a simple way to go from 0.5 to -0.5 but you can easily show the 0 value as being a fraction (eg -0.1) by modifying the value in your bar= line to:

bar <- ggplot(data = data, aes(x = date, fill=as.factor(purchasability),y = sapply(total_sold, FUN=function(x) ifelse(x==0, -0.1,x) ))) + geom_bar(stat = 'identity')

This produces: enter image description here

It is a little misleading to show 0 as something other than 0, but I hope this solves your problem.

ThatGuy
  • 1,225
  • 10
  • 28
  • Thank you for your answer. It does the job, but I tried to change the y lab with ylab="Sales Volume" but it keeps me the sapply. Can you please know how to edit that ? And also how to change the naming in the legend (as.factor(purchasability)) – user2741700 May 31 '14 at 11:32
  • Check out http://stackoverflow.com/questions/10438752/adding-x-and-y-axis-labels-in-ggplot2 - the syntax is ...+ylab("Sales Volume")... for the y-axis label. For the legend, see http://www.cookbook-r.com/Graphs/Legends_%28ggplot2%29/ - use ...+guides(fill=guide_legend(title="MY_TITLE"))... – ThatGuy May 31 '14 at 23:10