In 'Legend and colors' there is an option to color by dimension, in this case each dimension value is assigned to a color, and this is what is shown in legend.

In other cases the color are not directly related to dimension values, an expression can give a different color to a dimension value just because of different selections (changing the value returned for the expression and the color of a dimension value)