-2

I am trying to create a histogram for a variable which has both negative and positive values and I want to color the bars based on the sign of the variable, i.e., red if the number is negative and green if the number is positive. I am using the following code in ggplot2:

ggplot(aes(survey_grouped3$difference),data = survey_grouped3)+geom_histogram(binwidth = 10,fill = ifelse(survey_grouped3$difference >= 0,"green","red"))

But I am getting the following error:

Aesthetics must be either length 1 or the same as the data (26): fill

Can anyone help me on this? Thanks!

Edit: used the command

ggplot(survey_grouped3, aes(difference)) +geom_histogram(aes(fill=ifelse(difference > 0,"green","red")), binwidth = 10) +scale_color_identity()

but the coloring is still not working. i am attaching the output I am getting.

link to histogram

  • You should pre-bin your data and then use `geom_bar(stat = 'identitiy')`. As you have it, you have a bar that spans 0. What color should that be? – Gregor Thomas Jun 17 '16 at 17:48
  • Thank you so much for the suggestion. A bar chart would work better. apologies for my naivete, but can you assist me with the commands to pre-bin the data? – gagandeep91 Jun 17 '16 at 19:13
  • Use `cut` to define your bins. There are plenty of resources if you search the R tag for `bin data`. Someone might help out more explicitly [if you make your question reproducible](http://stackoverflow.com/q/5963269/903061) by sharing either simulated data or using `dput()` to share data. – Gregor Thomas Jun 17 '16 at 19:32

1 Answers1

1

You have to put the color part inside aes for it to be mapped from the data. Also, you don't need to specify the data frame when inside aes:

ggplot(survey_grouped3, aes(difference)) +
  geom_histogram(aes(fill=ifelse(difference > 0,"green","red")), binwidth = 10) +
  scale_color_identity() # So "red" and "green" actually map to red and green

Or if you don't intend to add anything else to the plot:

ggplot(survey_grouped3, aes(difference, fill=ifelse(difference > 0,"green","red"))) +
  geom_histogram(binwidth = 10) +
  scale_color_identity()
Felipe Gerard
  • 1,552
  • 13
  • 23