0

I am really new to R and GGPLOT and trying to create a chart with RAG colours based on the values in the Y axis- if a specific industry value is greater than all industries, it is green, if the same as all industries it is amber and if less than all industries it is red.

After much searching online I thought I had managed to crack it, but the bars I expect to be red are coming out blue- I've left the legend in the image as it shows what is going on. The thing is, I am not sure if I might be further away from success than I think- i.e. whether it is a fluke that the blue bars at the bottom have the label red.

To get a colour vector I adapted another code I found on stack overflow (lowest number is red through to highest being green, using logical values)

Bar_Colour <- c("red", "amber", "green")[
  (High_Cash_Reserves_Above0 < subset(High_Cash_Reserves_Above0,
           Cash_Reserves_Industry_Wrapped == "All Industries")) +
    2*(High_Cash_Reserves_Above0 == subset(
      High_Cash_Reserves_Above0,
      Cash_Reserves_Industry_Wrapped == "All Industries")) +
    3*(High_Cash_Reserves_Above0 > subset(
      High_Cash_Reserves_Above0,
      Cash_Reserves_Industry_Wrapped == "All Industries"))]
Bar_Colour

I then used this is to set the fill in the horizontal bar chart built using ggplot:

ggplot(
  BICS_Cash_Reserve_Above0,
  aes(
    reorder(
      Cash_Reserves_Industry_Wrapped,
      High_Cash_Reserves_Above0,
      sum
    ),
    High_Cash_Reserves_Above0, fill=Bar_Colour
  )) +
    geom_bar(stat = "identity", width = 0.95) +
    theme(axis.text.x = element_text(angle = 90, size = 0.04)) +
    coord_flip(
    )

Image of chart output that seems to show right labels but bars are blue, not red

I'd appreciate any advice on getting those bars red as this is a proof of concept piece and I feel like I am so close to generating this output using R (we currently do it in Excel, which is tiresome).

Thanks!

Ed

PS- unfortunately I cannot share underlying data as it is commercially sensitive

user7327273
  • 41
  • 1
  • 6
  • 2
    Try with `scale_fill_identity(guide = "legend")` to fill your bars according to the color names stored in `Bar_Colour`. – stefan Jan 27 '22 at 23:49
  • @stefan, please post as an answer ... – Ben Bolker Jan 28 '22 at 00:23
  • Related answer explaining same concept: https://stackoverflow.com/questions/29272550/use-color-names-specified-in-data-as-fill-color-in-geom-bar/29273729#29273729 – Jon Spring Jan 28 '22 at 00:55
  • Thanks very much Stefan and Jon Spring. Now all sorted. Turns out the other bits being green and amber was a fluke, but I wasn't as far off as I feared – user7327273 Jan 28 '22 at 14:17

0 Answers0