> ## Documentation Index
> Fetch the complete documentation index at: https://gocharting.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How to color bars by a condition

> Recoloring the chart's bars with barcolor and shading the pane with bgcolor, with the condition written inside the color argument.

Call `barcolor` at the top level and put the condition in its color argument. The color is a series value, so it may differ on every
bar. `barcolor` draws nothing of its own; it recolors the chart's bars.

```lipi theme={"languages":{"custom":["/languages/lipi.json","/languages/lipi-invalid.json"]}}
//@lipi=2
indicator("Up and down bars", overlay=true)
barcolor(close > open ? color.green : color.red, title="Direction")
```

## Color only some bars

Pass `na` as the color for the bars that should keep their own. `bgcolor` shades the pane background and takes the condition the
same way. `color.new(color, alpha)` sets the opacity from 0 (invisible) to 1 (solid), so use a low value for a light shade:

```lipi theme={"languages":{"custom":["/languages/lipi.json","/languages/lipi-invalid.json"]}}
//@lipi=2
indicator("Shaded wide bars", overlay=true)
bgcolor(high - low > close * 0.02 ? color.new(color.orange, 0.2) : na, title="Wide range")
```

## Color by a value

`color.from_gradient` blends two colors by where a value lies between two bounds:

```lipi theme={"languages":{"custom":["/languages/lipi.json","/languages/lipi-invalid.json"]}}
//@lipi=2
indicator("RSI shaded bars", overlay=true)
rsi = talib.rsi(close, 14)
barcolor(color.from_gradient(rsi, 30, 70, color.red, color.green), title="RSI")
```

`bgcolor` also takes `force_overlay=true`, which shades the price pane even when the script's plots sit in a pane of their own. `barcolor` has no such argument.

## The mistake to avoid

> [!WARNING]
>
> Putting the call inside an `if` to make it conditional. These calls must be at the top level, and the condition belongs in the
> argument:
>
> ```lipi-invalid theme={"languages":{"custom":["/languages/lipi.json","/languages/lipi-invalid.json"]}}
> //@lipi=2
> indicator("Branch")
> if close > open {
>     barcolor(color.green)
> }
> plot(close)
> ```

The compiler says: `barcolor()` must be called in the global scope.

The editor's check reports this. A related slip is giving `color.new` a percentage such as 50: it compiles with the warning
`opacity 50 is outside 0–1; 1 is solid`. See [Bar coloring and background](https://gocharting.com/docs/scripting/chart-output/bars-and-background.md) and
[Color and transparency](https://gocharting.com/docs/scripting/chart-output/color.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.