Plotting simple bar charts with Plots.jl with colors conditional on sign of values

I would like to create a bar chart that shows negative values of different color from positive values. I created a very simple example using x = 6 discrete time periods and y = 6 financial payoffs (2 of which are negative).

I attempted to specify a color for each financial payoff; this failed. What happened instead is that it took the first color and applied it to all 6 payoffs as opposed to applying each color to each payoff in sequence.

The simple plot code I am using is as follows (done within a Pluto notebook):

using Plots
x = 1:6 # This is a simple index across time periods 1 through 6.
y = [-50, -25, 0, 25, 50, 100] # this shows financial payoffs for time periods 1 through 6.
colors = [“#db5a44”, “#db5a44”, “#447adb”, “#447adb”, “#447adb”, “#447adb”]
plot(x, y, seriestype = :bar, legend=false, size=(800,500), palette = colors)

What is the suggested way to introduce conditional coloring to the bar chart data, keeping it as simple as possible using only the Plots.jl package?

A color is set per series, as discussed here: How to set labels for eached coloured bar in Plots.jl's bar()? - #6 by xiaodai

You could do:

julia> bar([[i] for i ∈ x], [[i] for i ∈ y], 
            color = permutedims(ifelse.(y .< 0, "#db5a44", "#447adb")), 
            label = "")

image

5 Likes

Excellent! This is exactly what I needed. Thank you nilshg.

2 Likes
plot(x[y .>= 0], y[y .>= 0]; seriestype=:bar, label="Positive")
plot!(x[y .< 0], y[y .< 0]; seriestype=:bar, label="Negative")

if you want them to be separate series with labels.

4 Likes