vaadinvaadin-flowvaadin14

Programmatically creating colors for Vaadin Chart series


In Vaadin 14.4.2, is it possible to create a Chart with multiple series in a way in which the color of the series is programmatically calculated? Specifically, I may have ~100 series, but they all are associated with a "number" (specifically a mass of a chemical element). Since I know what in my application the "number" (ie the mass) will range from 100 to 2000, I would like the color of the series to range from blue (at 100) to red (at 2000). This way, when a user looks at the graph, they intuitively know whether the series refers to a heavy chemical (red) or a light one (blue).

In order to accomplish this, I think I would need to have some way of programmatically setting the color of a series, but I do not think that's actually possible in Vaading 14.4.2, right?

Here's an example of such a chart: enter image description here


Solution

  • Color of the data series is defined by the custom properties --vaadin-charts-color-0, --vaadin-charts-color-1, ..., --vaadin-charts-color-9. You can programmatically define their values like follows

    charts.getElement().getStyle().set("--vaadin-charts-color-1","#2dd7a4");
    

    The second string parameter is the color value, it can be any format accepted in CSS.

    Update: This answer applies to Vaadin 14, which has Charts always in styled mode. Note: In Vaadin 23 you can select between styled mode (CSS) and setting colors via Java API.