First, you left out the code to reorder the country names factor by avg, so your code does not produce these plots.
Second, using a color name in a data frame doesn't help you. ggplot(...,aes(fill=...))
interprets that column as a factor to distinguish between groups. It assigns it's own colors, which is why you need to use scale_fill_manual(...)
to actually set the colors to something you want.
Third, you don't need breaks=...
in the call to scale_fill_manual(...)
.
Fourth, and this is the answer to your main question, unique(as.character(df$colours))
returns the colors in an order based on when they appear in df
. In the cash flow table, tan3
appears first, in the unemployment table grey
appears first. One way around this is to replace your calls
scale_fill_manual(breaks = df$Country.Name, values = unique(df$colour)))
with
scale_fill_manual(values =
as.character(setNames(unique(df$colour),unique(df$colour))))
with df
replaced by the names of your data frames. This creates a named vector of colors, where the color name and the color are the same, e.g.
c(tan3="tan3",grey="grey",NA)
which will associate the colors properly.
Finally, IMO you would be much better off doing something like this (here I'm using cash
as the name of your dataframe)
...
ggplot(data=cash,aes(x=Country.Name, y=avg,
fill=(ifelse(avg>0,"Positive","Negative"))))+
geom_bar(stat="identity",position=position_dodge(),
alpha=.75) +
scale_fill_manual(values = c(Positive="grey",Negative="tan3"))
...