Docs

Documentation versions (currently viewingVaadin 8)

Vaadin 8 reached End of Life on February 21, 2022. Discover how to make your Vaadin 8 app futureproof →

Chart Types

Vaadin Charts comes with over a dozen different chart types. You normally specify the chart type in the constructor of the Chart object. The available chart types are defined in the ChartType enum. You can later read or set the chart type with the chartType property of the chart model, which you can get with getConfiguration().getChart().

The supported chart types are:

area

arearange

areaspline

areasplinerange

bar

boxplot

bubble

column

columnrange

errorbar

flags

funnel

gauge

heatmap

line

pie

polygon

pyramid

scatter

solidgauge

sparkline

spline

treemap

waterfall

Each chart type has its specific plot options and support its specific collection of chart features. They also have specific requirements for the data series.

The basic chart types and their variants are covered in the following subsections.

Line and Spline Charts

Line charts connect the series of data points with lines. In the basic line charts the lines are straight, while in spline charts the lines are smooth polynomial interpolations between the data points.

Table 1. Line Chart Subtypes
ChartType Plot Options Class

LINE

PlotOptionsLine

SPLINE

PlotOptionsSpline

Plot Options

The color property in the line plot options defines the line color, lineWidth the line width, and dashStyle the dash pattern for the lines.

See Scatter Charts for plot options regarding markers and other data point properties. The markers can also be configured for each data point.

Area Charts

Area charts are like line charts, except that they fill the area between the line and some threshold value on Y axis. The threshold depends on the chart type. In addition to the base type, chart type combinations for spline interpolation and ranges are supported.

Table 2. Area Chart Subtypes
ChartType Plot Options Class

AREA

PlotOptionsArea

AREASPLINE

PlotOptionsAreaSpline

AREARANGE

PlotOptionsAreaRange

AREASPLINERANGE

PlotOptionsAreaSplineRange

In area range charts, the area between a lower and upper value is painted with a transparent color. The data series must specify the minimum and maximum values for the Y coordinates, defined either with RangeSeries, as described in "Range Series", or with DataSeries, described in "Generic Data Series".

Plot Options

Area charts support stacking, so that multiple series are piled on top of each other. You enable stacking from the plot options with setStacking(). The Stacking.NORMAL stacking mode does a normal summative stacking, while the Stacking.PERCENT handles them as proportions.

The fill color for the area is defined with the fillColor property and its transparency with fillOpacity (the opposite of transparency) with a value between 0.0 and 1.0.

The color property in the line plot options defines the line color, lineWidth the line width, and dashStyle the dash pattern for the lines.

See Scatter Charts for plot options regarding markers and other data point properties. The markers can also be configured for each data point.

Column and Bar Charts

Column and bar charts illustrate values as vertical or horizontal bars, respectively. The two chart types are essentially equivalent, just as if the orientation of the axes was inverted.

Multiple data series, that is, two-dimensional data, are shown with thinner bars or columns grouped by their category, as described in "Displaying Multiple Series". Enabling stacking with setStacking() in plot options stacks the columns or bars of different series on top of each other.

You can also have COLUMNRANGE charts that illustrate a range between a lower and an upper value, as described in Area and Column Range Charts. They require the use of RangeSeries for defining the lower and upper values.

Table 3. Column and Bar Chart Subtypes
ChartType Plot Options Class

COLUMN

PlotOptionsColumn

COLUMNRANGE

PlotOptionsColumnRange

BAR

PlotOptionsBar

See the API documentation for details regarding the plot options.

Error Bars

An error bars visualize errors, or high and low values, in statistical data. They typically represent high and low values in data or a multitude of standard deviation, a percentile, or a quantile. The high and low values are represented as horizontal lines, or "whiskers", connected by a vertical stem.

While error bars technically are a chart type ( ChartType.ERRORBAR), you normally use them together with some primary chart type, such as a scatter or column chart.

charts errorbar
Error Bars in a Scatter Chart

To display the error bars for data points, you need to have a separate data series for the low and high values. The data series needs to use the PlotOptionsErrorBar plot options type.

// Create a chart of some primary type
Chart chart = new Chart(ChartType.SCATTER);
chart.setWidth("600px");
chart.setHeight("400px");

// Modify the default configuration a bit
Configuration conf = chart.getConfiguration();
conf.setTitle("Average Temperatures in Turku");
conf.getLegend().setEnabled(false);

// The primary data series
ListSeries averages = new ListSeries(
    -6, -6.5, -4, 3, 9, 14, 17, 16, 11, 6, 2, -2.5);

// Error bar data series with low and high values
DataSeries errors = new DataSeries();
errors.add(new DataSeriesItem(0,  -9, -3));
errors.add(new DataSeriesItem(1, -10, -3));
errors.add(new DataSeriesItem(2,  -8,  1));
...

// Configure the stem and whiskers in error bars
PlotOptionsErrorbar barOptions = new PlotOptionsErrorbar();
barOptions.setStemColor(SolidColor.GREY);
barOptions.setStemWidth(2);
barOptions.setStemDashStyle(DashStyle.DASH);
barOptions.setWhiskerColor(SolidColor.BROWN);
barOptions.setWhiskerLength(80, Sizeable.Unit.PERCENTAGE); // 80% of category width
barOptions.setWhiskerWidth(2); // Pixels
errors.setPlotOptions(barOptions);

// The errors should be drawn lower
conf.addSeries(errors);
conf.addSeries(averages);

Note that you should add the error bar series first, to have it rendered lower in the chart.

Plot Options

Plot options for error bar charts have type PlotOptionsErrorBar. It has the following chart-specific plot option properties:

whiskerColor, whiskerWidth, and whiskerLength

The color, width (vertical thickness), and length of the horizontal "whiskers" that indicate high and low values.

stemColor, stemWidth, and stemDashStyle

The color, width (thickness), and line style of the vertical "stems" that connect the whiskers. In box plot charts, which also have stems, they extend from the quadrintile box.

Box Plot Charts

Box plot charts display the distribution of statistical variables. A data point has a median, represented with a horizontal line, upper and lower quartiles, represented by a box, and a low and high value, represented with T-shaped "whiskers". The exact semantics of the box symbols are up to you.

Box plot chart is closely related to the error bar chart described in Error Bars, sharing the box and whisker elements.

charts boxplot
Box Plot Chart

The chart type for box plot charts is ChartType.BOXPLOT. You normally have just one data series, so it is meaningful to disable the legend.

Chart chart = new Chart(ChartType.BOXPLOT);
chart.setWidth("400px");
chart.setHeight("300px");

// Modify the default configuration a bit
Configuration conf = chart.getConfiguration();
conf.setTitle("Orienteering Split Times");
conf.getLegend().setEnabled(false);

Plot Options

The plot options for box plots have type PlotOptionsBoxPlot, which extends the slightly more generic PlotOptionsErrorBar. They have the following plot option properties:

medianColor,medianWidth

Color and width (vertical thickness) of the horizontal median indicator line.

For example:

// Set median line color and thickness
PlotOptionsBoxplot plotOptions = new PlotOptionsBoxplot();
plotOptions.setMedianColor(SolidColor.BLUE);
plotOptions.setMedianWidth(3);
conf.setPlotOptions(plotOptions);

Data Model

As the data points in box plots have five different values instead of the usual one, they require using a special BoxPlotItem. You can give the different values with the setters, or all at once in the constructor.

// Orienteering control point times for runners
double data[][] = orienteeringdata();

DataSeries series = new DataSeries();
for (double cpointtimes[]: data) {
    StatAnalysis analysis = new StatAnalysis(cpointtimes);
    series.add(new BoxPlotItem(analysis.low(),
                               analysis.firstQuartile(),
                               analysis.median(),
                               analysis.thirdQuartile(),
                               analysis.high()));
}
conf.setSeries(series);

If the "low" and "high" attributes represent an even smaller quantile, or a larger multiple of standard deviation, you can have outliers. You can plot them with a separate data series, with

Scatter Charts

Scatter charts display a set of unconnected data points. The name refers to freely given X and Y coordinates, so the DataSeries or ContainerSeries are usually the most meaningful data series types for scatter charts.

charts scatter
Scatter Chart

The chart type of a scatter chart is ChartType.SCATTER. Its options can be configured in a PlotOptionsScatter object, although it does not have any chart-type specific options.

Chart chart = new Chart(ChartType.SCATTER);
chart.setWidth("500px");
chart.setHeight("500px");

// Modify the default configuration a bit
Configuration conf = chart.getConfiguration();
conf.setTitle("Random Sphere");
conf.getLegend().setEnabled(false); // Disable legend

PlotOptionsScatter options = new PlotOptionsScatter();
// ... Give overall plot options here ...
conf.setPlotOptions(options);

DataSeries series = new DataSeries();
for (int i=0; i<300; i++) {
    double lng = Math.random() * 2 * Math.PI;
    double lat = Math.random() * Math.PI - Math.PI/2;
    double x   = Math.cos(lat) * Math.sin(lng);
    double y   = Math.sin(lat);
    double z   = Math.cos(lng) * Math.cos(lat);

    DataSeriesItem point = new DataSeriesItem(x,y);
    Marker marker = new Marker();
    // Make settings as described later
    point.setMarker(marker);
    series.add(point);
}
conf.addSeries(series);

The result was shown in Scatter Chart.

Data Point Markers

Scatter charts and other charts that display data points, such as line and spline charts, visualize the points with markers. The markers can be configured with the Marker property objects available from the plot options of the relevant chart types, as well as at the level of each data point, in the DataSeriesItem. You need to create the marker and apply it with the setMarker() method in the plot options or the data series item.

For example, to set the marker for an individual data point:

DataSeriesItem point = new DataSeriesItem(x,y);
Marker marker = new Marker();
// ... Make any settings ...
point.setMarker(marker);
series.add(point);

Marker Shape Properties

A marker has a lineColor and a fillColor, which are set using a Color object. Both solid colors and gradients are supported. You can use a SolidColor to specify a solid fill color by RGB values or choose from a selection of predefined colors in the class.

// Set line width and color
marker.setLineWidth(1); // Normally zero width
marker.setLineColor(SolidColor.BLACK);

// Set RGB fill color
int level = (int) Math.round((1-z)*127);
marker.setFillColor(
        new SolidColor(255-level, 0, level));
point.setMarker(marker);
series.add(point);

You can also use a color gradient with GradientColor. Both linear and radial gradients are supported, with multiple color stops.

Marker size is determined by the radius parameter, which is given in pixels. The actual visual radius includes also the line width.

marker.setRadius((z+1)*5);

Marker Symbols

Markers are visualized either with a shape or an image symbol. You can choose the shape from a number of built-in shapes defined in the MarkerSymbolEnum enum ( CIRCLE, SQUARE, DIAMOND, TRIANGLE, or TRIANGLE_DOWN). These shapes are drawn with a line and fill, which you can set as described above.

marker.setSymbol(MarkerSymbolEnum.DIAMOND);

You can also use any image accessible by a URL by using a MarkerSymbolUrl symbol. If the image is deployed with your application, such as in a theme folder, you can determine its URL as follows:

String url = VaadinServlet.getCurrent().getServletContext()
    .getContextPath() + "/VAADIN/themes/mytheme/img/smiley.png";
marker.setSymbol(new MarkerSymbolUrl(url));

The line, radius, and color properties are not applicable to image symbols.

Bubble Charts

Bubble charts are a special type of scatter charts for representing three-dimensional data points with different point sizes. We demonstrated the same possibility with scatter charts in Scatter Charts, but the bubble charts make it easier to define the size of a point by its third (Z) dimension, instead of the radius property. The bubble size is scaled automatically, just like for other dimensions. The default point style is also more bubbly.

charts bubble
Bubble Chart

The chart type of a bubble chart is ChartType.BUBBLE. Its options can be configured in a PlotOptionsBubble object, which has a single chart-specific property, displayNegative, which controls whether bubbles with negative values are displayed at all. More typically, you want to configure the bubble marker. The bubble tooltip is configured in the basic configuration. The Z coordinate value is available in the formatter JavaScript with this.point.z reference.

The bubble radius is scaled linearly between a minimum and maximum radius. If you would rather scale by the area of the bubble, you can approximate that by taking square root of the Z values.

In the following example, we overlay a bubble chart over a world map background. We customize the bubbles to be more round with spherical color gradient. Note that square root is taken of the Z coordinate to

// Create a bubble chart
Chart chart = new Chart(ChartType.BUBBLE);
chart.setWidth("640px"); chart.setHeight("350px");

// Modify the default configuration a bit
Configuration conf = chart.getConfiguration();
conf.setTitle("Champagne Consumption by Country");
conf.getLegend().setEnabled(false); // Disable legend
conf.getTooltip().setFormatter("this.point.name + ': ' + " +
  "Math.round(100*(this.point.z * this.point.z))/100.0 + " +
  "' M bottles'");

// World map as background
String url = VaadinServlet.getCurrent().getServletContext()
    .getContextPath() + "/VAADIN/themes/mytheme/img/map.png";
conf.getChart().setPlotBackgroundImage(url);

// Show more bubbly bubbles with spherical color gradient
PlotOptionsBubble plotOptions = new PlotOptionsBubble();
Marker marker = new Marker();
GradientColor color = GradientColor.createRadial(0.4, 0.3, 0.7);
color.addColorStop(0.0, new SolidColor(255, 255, 255, 0.5));
color.addColorStop(1.0, new SolidColor(170, 70, 67, 0.5));
marker.setFillColor(color);
plotOptions.setMarker(marker);
conf.setPlotOptions(plotOptions);

// Source: CIVC - Les expeditions de vins de Champagne en 2011
DataSeries series = new DataSeries("Countries");
Object data[][] = {
        {"France",         181.6},
        {"United Kingdom",  34.53},
        {"United States",   19.37},
        ...
};
for (Object[] country: data) {
    String name = (String) country[0];
    double amount = (Double) country[1];
    Coordinate pos = getCountryCoordinates(name);

    DataSeriesItem3d item = new DataSeriesItem3d();
    item.setX(pos.longitude * Math.cos(pos.latitude/2.0 *
                                       (Math.PI/160)));
    item.setY(pos.latitude * 1.2);
    item.setZ(Math.sqrt(amount));
    item.setName(name);
    series.add(item);
}
conf.addSeries(series);

// Set the category labels on the axis correspondingly
XAxis xaxis = new XAxis();
xaxis.setExtremes(-180, 180);
...
conf.addxAxis(xaxis);

// Set the Y axis title
YAxis yaxis = new YAxis();
yaxis.setExtremes(-90, 90);
...
conf.addyAxis(yaxis);

Pie Charts

A pie chart illustrates data values as sectors of size proportionate to the sum of all values. The pie chart is enabled with ChartType.PIE and you can make type-specific settings in the PlotOptionsPie object as described later.

Chart chart = new Chart(ChartType.PIE);
Configuration conf = chart.getConfiguration();
...

A ready pie chart is shown in Pie Chart.

charts pie
Pie Chart

Plot Options

The chart-specific options of a pie chart are configured with a PlotOptionsPie.

PlotOptionsPie options = new PlotOptionsPie();
options.setInnerSize("0");
options.setSize("75%");  // Default
options.setCenter("50%", "50%"); // Default
conf.setPlotOptions(options);
innerSize

A pie with inner size greater than zero is a "donut". The inner size can be expressed either as number of pixels or as a relative percentage of the chart area with a string (such as "60%") See the section later on donuts.

size

The size of the pie can be expressed either as number of pixels or as a relative percentage of the chart area with a string (such as "80%"). The default size is 75%, to leave space for the labels.

center

The X and Y coordinates of the center of the pie can be expressed either as numbers of pixels or as a relative percentage of the chart sizes with a string. The default is "50%", "50%".

Data Model

The labels for the pie sectors are determined from the labels of the data points. The DataSeries or ContainerSeries, which allow labeling the data points, should be used for pie charts.

DataSeries series = new DataSeries();
series.add(new DataSeriesItem("Mercury", 4900));
series.add(new DataSeriesItem("Venus", 12100));
...
conf.addSeries(series);

If a data point, as defined as a DataSeriesItem in a DataSeries, has the sliced property enabled, it is shown as slightly cut away from the pie.

// Slice one sector out
DataSeriesItem earth = new DataSeriesItem("Earth", 12800);
earth.setSliced(true);
series.add(earth);

Donut Charts

Setting the innerSize of the plot options of a pie chart to a larger than zero value results in an empty hole at the center of the pie.

PlotOptionsPie options = new PlotOptionsPie();
options.setInnerSize("60%");
conf.setPlotOptions(options);

As you can set the plot options also for each data series, you can put two pie charts on top of each other, with a smaller one fitted in the "hole" of the donut. This way, you can make pie charts with more details on the outer rim, as done in the example below:

// The inner pie
DataSeries innerSeries = new DataSeries();
innerSeries.setName("Browsers");
PlotOptionsPie innerPieOptions = new PlotOptionsPie();
innerPieOptions.setSize("60%");
innerSeries.setPlotOptions(innerPieOptions);
...

DataSeries outerSeries = new DataSeries();
outerSeries.setName("Versions");
PlotOptionsPie outerSeriesOptions = new PlotOptionsPie();
outerSeriesOptions.setInnerSize("60%");
outerSeries.setPlotOptions(outerSeriesOptions);
...

The result is illustrated in Overlaid Pie and Donut Chart.

charts donut
Overlaid Pie and Donut Chart

Gauges

A gauge is an one-dimensional chart with a circular Y-axis, where a rotating pointer points to a value on the axis. A gauge can, in fact, have multiple Y-axes to display multiple scales.

A solid gauge is otherwise like a regular gauge, except that a solid color arc is used to indicate current value instead of a pointer. The color of the indicator arc can be configured to change according to color stops.

Let us consider the following gauge:

Chart chart = new Chart(ChartType.GAUGE);
chart.setWidth("400px");
chart.setHeight("400px");

After the settings done in the subsequent sections, it will show as in A Gauge.

charts gauge
A Gauge

Gauge Configuration

The start and end angles of the gauge can be configured in the Pane object of the chart configuration. The angles can be given as -360 to 360 degrees, with 0 at the top of the circle.

Configuration conf = chart.getConfiguration();
conf.setTitle("Speedometer");
conf.getPane().setStartAngle(-135);
conf.getPane().setEndAngle(135);

Axis Configuration

A gauge has only an Y-axis. You need to provide both a minimum and maximum value for it.

YAxis yaxis = new YAxis();
yaxis.setTitle("km/h");

// The limits are mandatory
yaxis.setMin(0);
yaxis.setMax(100);

// Other configuration
yaxis.getLabels().setStep(1);
yaxis.setTickInterval(10);
yaxis.setTickLength(10);
yaxis.setTickWidth(1);
yaxis.setMinorTickInterval("1");
yaxis.setMinorTickLength(5);
yaxis.setMinorTickWidth(1);
yaxis.setPlotBands(new PlotBand[]{
        new PlotBand(0,  60,  SolidColor.GREEN),
        new PlotBand(60, 80,  SolidColor.YELLOW),
        new PlotBand(80, 100, SolidColor.RED)});
yaxis.setGridLineWidth(0); // Disable grid

conf.addyAxis(yaxis);

You can do all kinds of other configuration to the axis - please see the API documentation for all the available parameters.

Setting and Updating Gauge Data

A gauge only displays a single value, which you can define as a data series of length one, such as as follows:

ListSeries series = new ListSeries("Speed", 80);
conf.addSeries(series);

Gauges are especially meaningful for displaying changing values. You can use the updatePoint() method in the data series to update the single value.

final TextField tf = new TextField("Enter a new value");
layout.addComponent(tf);

Button update = new Button("Update", new ClickListener() {
    @Override
    public void buttonClick(ClickEvent event) {
        Integer newValue = new Integer((String)tf.getValue());
        series.updatePoint(0, newValue);
    }
});
layout.addComponent(update);

Solid Gauges

A solid gauge is much like a regular gauge described previously; a one-dimensional chart with a circular Y-axis. However, instead of a rotating pointer, the value is indicated by a rotating arc with solid color. The color of the indicator arc can be configured to change according to the value using color stops.

Let us consider the following gauge:

Chart chart = new Chart(ChartType.SOLIDGAUGE);
chart.setWidth("400px");
chart.setHeight("400px");

After the settings done in the subsequent sections, it will show as in A Solid Gauge.

charts solidgauge
A Solid Gauge

While solid gauge is much like a regular gauge, the configuration differs

Configuration

The solid gauge must be configured in the drawing Pane of the chart configuration. The gauge arc spans an angle, which is specified as -360 to 360 degrees, with 0 degrees at the top of the arc. Typically, a semi-arc is used, where you use -90 and 90 for the angles, and move the center lower than you would have with a full circle. You can also adjust the size of the gauge pane; enlargening it allows positioning tick labels better.

Configuration conf = chart.getConfiguration();
conf.setTitle("Solid Gauge");

Pane pane = conf.getPane();
pane.setSize("125%");           // For positioning tick labels
pane.setCenter("50%", "70%"); // Move center lower
pane.setStartAngle(-90);        // Make semi-circle
pane.setEndAngle(90);           // Make semi-circle

The shape of the gauge display is defined as the background of the pane. You at least need to set the shape as either " arc" or " solid". You typically also want to set background color and inner and outer radius.

Background bkg = new Background();
bkg.setBackgroundColor(new SolidColor("#eeeeee")); // Gray
bkg.setInnerRadius("60%");  // To make it an arc and not circle
bkg.setOuterRadius("100%"); // Default - not necessary
bkg.setShape("arc");        // solid or arc
pane.setBackground(bkg);

Axis Configuration

A gauge only has an Y-axis. You must define the value range ( min and max).

YAxis yaxis = new YAxis();
yaxis.setTitle("Pressure GPa");
yaxis.getTitle().setY(-80); // Move 70 px upwards from center

// The limits are mandatory
yaxis.setMin(0);
yaxis.setMax(200);

// Configure ticks and labels
yaxis.setTickInterval(100);  // At 0, 100, and 200
yaxis.getLabels().setY(-16); // Move 16 px upwards
yaxis.setGridLineWidth(0); // Disable grid

You can configure color stops for the indicator arc. The stops are defined with Stop objects having stop points from 0.0 to 1.0 and color values.

yaxis.setStops(new Stop(0.1f, SolidColor.GREEN),
               new Stop(0.5f, SolidColor.YELLOW),
               new Stop(0.9f, SolidColor.RED));

conf.addyAxis(yaxis);

Setting yaxis.getLabels().setRotationPerpendicular() makes gauge labels rotate perpendicular to the center.

You can do all kinds of other configuration to the axis - please see the API documentation for all the available parameters.

Plot Options

Solid gauges do not currently have any chart type specific plot options. See "Plot Options" for common options.

PlotOptionsSolidgauge options = new PlotOptionsSolidgauge();

// Move the value display box at the center a bit higher
Labels dataLabels = new Labels();
dataLabels.setY(-20);
options.setDataLabels(dataLabels);

conf.setPlotOptions(options);

Setting and Updating Gauge Data

A gauge only displays a single value, which you can define as a data series of length one, such as as follows:

ListSeries series = new ListSeries("Pressure MPa", 80);
conf.addSeries(series);

Gauges are especially meaningful for displaying changing values. You can use the updatePoint() method in the data series to update the single value.

final TextField tf = new TextField("Enter a new value");
layout.addComponent(tf);

Button update = new Button("Update", new ClickListener() {
    @Override
    public void buttonClick(ClickEvent event) {
        Integer newValue = new Integer((String)tf.getValue());
        series.updatePoint(0, newValue);
    }
});
layout.addComponent(update);

Area and Column Range Charts

Ranged charts display an area or column between a minimum and maximum value, instead of a singular data point. They require the use of RangeSeries, as described in "Range Series". An area range is created with AREARANGE chart type, and a column range with COLUMNRANGE chart type.

Consider the following example:

Chart chart = new Chart(ChartType.AREARANGE);
chart.setWidth("400px");
chart.setHeight("300px");

// Modify the default configuration a bit
Configuration conf = chart.getConfiguration();
conf.setTitle("Extreme Temperature Range in Finland");
...

// Create the range series
// Source: https://ilmatieteenlaitos.fi/lampotilaennatyksia
RangeSeries series = new RangeSeries("Temperature Extremes",
    new Double[]{-51.5,10.9},
    new Double[]{-49.0,11.8},
    ...
    new Double[]{-47.0,10.8});//
conf.addSeries(series);

The resulting chart, as well as the same chart with a column range, is shown in Area and Column Range Chart.

charts arearange
Area and Column Range Chart

Polar, Wind Rose, and Spiderweb Charts

Most chart types having two axes can be displayed in polar coordinates, where the X axis is curved on a circle and Y axis from the center of the circle to its rim. Polar chart is not a chart type in itself, but can be enabled for most chart types with setPolar(true) in the chart model parameters. Therefore all chart type specific features are usable with polar charts.

Vaadin Charts allows many sorts of typical polar chart types, such as wind rose, a polar column graph, or spiderweb, a polar chart with categorical data and a more polygonal visual style.

// Create a chart of some type
Chart chart = new Chart(ChartType.LINE);

// Enable the polar projection
Configuration conf = chart.getConfiguration();
conf.getChart().setPolar(true);

You need to define the sector of the polar projection with a Pane object in the configuration. The sector is defined as degrees from the north direction. You also need to define the value range for the X axis with setMin() and setMax().

// Define the sector of the polar projection
Pane pane = new Pane(0, 360); // Full circle
conf.addPane(pane);

// Define the X axis and set its value range
XAxis axis = new XAxis();
axis.setMin(0);
axis.setMax(360);

The polar and spiderweb charts are illustrated in Wind Rose and Spiderweb Charts.

charts polarspiderweb
Wind Rose and Spiderweb Charts

Spiderweb Charts

A spiderweb chart is a commonly used visual style of a polar chart with a polygonal shape rather than a circle. The data and the X axis should be categorical to make the polygonal interpolation meaningful. The sector is assumed to be full circle, so no angles for the pane need to be specified.

Note the style settings done in the axis in the example below:

Chart chart = new Chart(ChartType.LINE);
...

// Modify the default configuration a bit
Configuration conf = chart.getConfiguration();
conf.getChart().setPolar(true);
...

// Create the range series
// Source: https://ilmatieteenlaitos.fi/lampotilaennatyksia
ListSeries series = new ListSeries("Temperature Extremes",
    10.9, 11.8, 17.5, 25.5, 31.0, 33.8,
    37.2, 33.8, 28.8, 19.4, 14.1, 10.8);
conf.addSeries(series);

// Set the category labels on the X axis correspondingly
XAxis xaxis = new XAxis();
xaxis.setCategories("Jan", "Feb", "Mar",
    "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec");
xaxis.setTickmarkPlacement(TickmarkPlacement.ON);
xaxis.setLineWidth(0);
conf.addxAxis(xaxis);

// Configure the Y axis
YAxis yaxis = new YAxis();
yaxis.setGridLineInterpolation("polygon"); // Webby look
yaxis.setMin(0);
yaxis.setTickInterval(10);
yaxis.getLabels().setStep(1);
conf.addyAxis(yaxis);

Funnel and Pyramid Charts

Funnel and pyramid charts are typically used to visualize stages in a sales processes, and for other purposes to visualize subsets of diminishing size. A funnel or pyramid chart has layers much like a stacked column: in funnel from top-to-bottom and in pyramid from bottom-to-top. The top of the funnel has width of the drawing area of the chart, and dinimishes in size down to a funnel "neck" that continues as a column to the bottom. A pyramid diminishes from bottom to top and does not have a neck.

charts funnel
Funnel and Pyramid Charts

Funnels have chart type FUNNEL, pyramids have PYRAMID.

The labels of the funnel blocks are by default placed on the right side of the blocks, together with a connector. You can configure their style in the plot options. See the following example.

Chart chart = new Chart(ChartType.FUNNEL);
chart.setWidth("500px");
chart.setHeight("350px");

// Modify the default configuration a bit
Configuration conf = chart.getConfiguration();
conf.setTitle("Monster Utilization");
conf.getLegend().setEnabled(false);

// Give more room for the labels
conf.getChart().setSpacingRight(120);

// Configure the funnel neck shape
PlotOptionsFunnel options = new PlotOptionsFunnel();
options.setNeckHeight(20, Sizeable.Unit.PERCENTAGE);
options.setNeckWidth(20, Sizeable.Unit.PERCENTAGE);

// Style the data labels
DataLabelsFunnel dataLabels = new DataLabelsFunnel();
dataLabels.setFormat("<b>{point.name}</b> ({point.y:,.0f})");
dataLabels.setSoftConnector(false);
dataLabels.setColor(SolidColor.BLACK);
options.setDataLabels(dataLabels);

conf.setPlotOptions(options);

// Create the range series
DataSeries series = new DataSeries();
series.add(new DataSeriesItem("Monsters Met", 340));
series.add(new DataSeriesItem("Engaged", 235));
series.add(new DataSeriesItem("Killed", 187));
series.add(new DataSeriesItem("Tinned", 70));
series.add(new DataSeriesItem("Eaten", 55));
conf.addSeries(series);

Plot Options

The funnel and pyramid options are configured with PlotOptionsFunnel or PlotOptionsFunnel, respectively.

In addition to common chart options, the chart types support the following shared options: width, height, depth, allowPointSelect, borderColor, borderWidth, center, slicedOffset, and visible. See "Plot Options" for detailed descriptions.

They have the following chart type specific properties:

neckHeight#or[parameter]#neckHeightPercentage (only funnel)

Height of the neck part of the funnel either as pixels or as percentage of the entire funnel height.

neckWidth#or[parameter]#neckWidthPercentage (only funnel)

Width of the neck part of the funnel either as pixels or as percentage of the top of the funnel.

reversed

Whether the chart is reversed upside down from the normal direction from diminishing from the top to bottom. The default is false for funnel and true for pyramid.

Waterfall Charts

Waterfall charts are used for visualizing level changes from an initial level to a final level through a number of changes in the level. The changes are given as delta values, and you can have a number of intermediate totals, which are calculated automatically.

charts waterfall
Waterfall Charts

Waterfall charts have chart type WATERFALL.

For example:

Chart chart = new Chart(ChartType.WATERFALL);
chart.setWidth("500px");
chart.setHeight("350px");

// Modify the default configuration a bit
Configuration conf = chart.getConfiguration();
conf.setTitle("Changes in Reindeer Population in 2011");
conf.getLegend().setEnabled(false);

// Configure X axis
XAxis xaxis = new XAxis();
xaxis.setCategories("Start", "Predators", "Slaughter",
    "Reproduction", "End");
conf.addxAxis(xaxis);

// Configure Y axis
YAxis yaxis = new YAxis();
yaxis.setTitle("Population (thousands)");
conf.addyAxis(yaxis);
...

The example continues in the following subsections.

Plot Options

Waterfall charts have plot options type PlotOptionsWaterfall, which extends the more general options defined in PlotOptionsColumn. It has the following chart type specific properties:

upColor

Color for the positive values.

color

Default color for all the points. If upColor is defined, color is used only for the negative values.

In the following, we define the colors, as well as the style and placement of the labels for the columns:

// Define the colors
final Color balanceColor = SolidColor.BLACK;
final Color positiveColor = SolidColor.BLUE;
final Color negativeColor = SolidColor.RED;

// Configure the colors
PlotOptionsWaterfall options = new PlotOptionsWaterfall();
options.setUpColor(positiveColor);
options.setColor(negativeColor);

// Configure the labels
Labels labels = new Labels(true);
labels.setVerticalAlign(VerticalAlign.TOP);
labels.setY(-20);
labels.setFormatter("Math.floor(this.y/1000) + 'k'");
Style style = new Style();
style.setColor(SolidColor.BLACK);
style.setFontWeight(FontWeight.BOLD);
labels.setStyle(style);
options.setDataLabels(labels);
options.setPointPadding(0);
conf.setPlotOptions(options);

Data Series

The data series for waterfall charts consists of changes (deltas) starting from an initial value and one or more cumulative sums. There should be at least a final sum, and optionally intermediate sums. The sums are represented as WaterFallSum data items, and no value is needed for them as they are calculated automatically. For intermediate sums, you should set the intermediate property to true.

// The data
DataSeries series = new DataSeries();

// The beginning balance
DataSeriesItem start = new DataSeriesItem("Start", 306503);
start.setColor(balanceColor);
series.add(start);

// Deltas
series.add(new DataSeriesItem("Predators", -3330));
series.add(new DataSeriesItem("Slaughter", -103332));
series.add(new DataSeriesItem("Reproduction", +104052));

WaterFallSum end = new WaterFallSum("End");
end.setColor(balanceColor);
end.setIntermediate(false); // Not intermediate (default)
series.add(end);

conf.addSeries(series);

Heat Maps

A heat map is a two-dimensional grid, where the color of a grid cell indicates a value.

charts heatmap
Heat Maps

Heat maps have chart type HEATMAP.

For example:

Chart chart = new Chart(ChartType.HEATMAP);
chart.setWidth("600px");
chart.setHeight("300px");

Configuration conf = chart.getConfiguration();
conf.setTitle("Heat Data");

// Set colors for the extremes
conf.getColorAxis().setMinColor(SolidColor.AQUA);
conf.getColorAxis().setMaxColor(SolidColor.RED);

// Set up border and data labels
PlotOptionsHeatmap plotOptions = new PlotOptionsHeatmap();
plotOptions.setBorderColor(SolidColor.WHITE);
plotOptions.setBorderWidth(2);
plotOptions.setDataLabels(new DataLabels(true));
conf.setPlotOptions(plotOptions);

// Create some data
HeatSeries series = new HeatSeries();
series.addHeatPoint( 0, 0,  10.9); // Jan High
series.addHeatPoint( 0, 1, -51.5); // Jan Low
series.addHeatPoint( 1, 0,  11.8); // Feb High
...
series.addHeatPoint(11, 1, -47.0); // Dec Low
conf.addSeries(series);

// Set the category labels on the X axis
XAxis xaxis = new XAxis();
xaxis.setTitle("Month");
xaxis.setCategories("Jan", "Feb", "Mar",
    "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec");
conf.addxAxis(xaxis);

// Set the category labels on the Y axis
YAxis yaxis = new YAxis();
yaxis.setTitle("");
yaxis.setCategories("High C", "Low C");
conf.addyAxis(yaxis);

Heat Map Data Series

Heat maps require two-dimensional tabular data. The easiest way is to use HeatSeries, as was done in the example earlier. You can add data points with the addHeatPoint() method, or give all the data at once in an array with setData() or in the constructor.

If you need to use other data series type for a heat map, notice that the semantics of the heat map data points are currently not supported by the general-purpose series types, such as DataSeries. You can work around this semantic limitation by specifying the X (column), Y (row), and heatScore by using the respective X, low, and high properties of the general-purpose data series.

Also note that while some other data series types allow updating the values one by one, updating all the values in a heat map is very inefficient; it is faster to simply replace the data series and then call chart.drawChart().

Tree Maps

A tree map is used to display hierarchical data. It consists of a group of rectangles that contains other rectangles, where the size of a rectangle indicates the item value.

charts treemap
Tree Maps

Tree maps have chart type TREEMAP.

For example:

Chart chart = new Chart();

PlotOptionsTreemap plotOptions = new PlotOptionsTreemap();
plotOptions.setLayoutAlgorithm(TreeMapLayoutAlgorithm.STRIPES);
plotOptions.setAlternateStartingDirection(true);

Level level = new Level();
level.setLevel(1);
level.setLayoutAlgorithm(TreeMapLayoutAlgorithm.SLICEANDDICE);

DataLabels dataLabels = new DataLabels();
dataLabels.setEnabled(true);
dataLabels.setAlign(HorizontalAlign.LEFT);
dataLabels.setVerticalAlign(VerticalAlign.TOP);

Style style = new Style();
style.setFontSize("15px");
style.setFontWeight(FontWeight.BOLD);

dataLabels.setStyle(style);
level.setDataLabels(dataLabels);
plotOptions.setLevels(level);

TreeSeries series = new TreeSeries();

TreeSeriesItem apples = new TreeSeriesItem("A", "Apples");
apples.setColor(new SolidColor("#EC2500"));

TreeSeriesItem bananas = new TreeSeriesItem("B", "Bananas");
bananas.setColor(new SolidColor("#ECE100"));

TreeSeriesItem oranges = new TreeSeriesItem("O", "Oranges");
oranges.setColor(new SolidColor("#EC9800"));

TreeSeriesItem anneA = new TreeSeriesItem("Anne", apples, 5);
TreeSeriesItem rickA = new TreeSeriesItem("Rick", apples, 3);
TreeSeriesItem paulA = new TreeSeriesItem("Paul", apples, 4);

TreeSeriesItem anneB = new TreeSeriesItem("Anne", bananas, 4);
TreeSeriesItem rickB = new TreeSeriesItem("Rick", bananas, 10);
TreeSeriesItem paulB = new TreeSeriesItem("Paul", bananas, 1);

TreeSeriesItem anneO = new TreeSeriesItem("Anne", oranges, 1);
TreeSeriesItem rickO = new TreeSeriesItem("Rick", oranges, 3);
TreeSeriesItem paulO = new TreeSeriesItem("Paul", oranges, 3);

TreeSeriesItem susanne = new TreeSeriesItem("Susanne", 2);
susanne.setParent("Kiwi");
susanne.setColor(new SolidColor("#9EDE00"));

series.addAll(apples, bananas, oranges, anneA, rickA, paulA,
        anneB, rickB, paulB, anneO, rickO, paulO, susanne);

series.setPlotOptions(plotOptions);

chart.getConfiguration().addSeries(series);

chart.getConfiguration().setTitle("Fruit consumption");

Plot Options

Tree map charts have plot options type PlotOptionsTreeMap, which extends the more general options defined in AbstractCommonOptionsColumn. It has the following chart type specific properties:

allowDrillToNode

When enabled the user can click on a point which is a parent and zoom in on its children. Defaults to false.

alternateStartingDirection

Enabling this option will make the treemap alternate the drawing direction between vertical and horizontal. The next levels starting direction will always be the opposite of the previous. Defaults value is false.

layoutAlgorithm

This option decides which algorithm is used for setting position and dimensions of the points. Available algorithms are defined in TreeMapLayoutAlgorithm enum: SLICEANDDICE, STRIPES, SQUARIFIED and STRIP. Default value is SLICEANDDICE.

layoutStartingDirection

Defines which direction the layout algorithm will start drawing. Possible values are defined in TreeMapLayoutStartingDirection enum: HORIZONTAL and VERTICAL. Default value is VERTICAL.

levelIsConstant

Used together with the setLevels() and setAllowDrillToNode() options. When set to false the first level visible when drilling is considered to be level one. Otherwise the level will be the same as the tree structure. Defaults value is true.

levels

Set options on specific levels. Takes precedence over series options, but not point options.

Tree Map Data Series

Tree maps require hierarchical data. The easiest way is to use TreeSeries and TreeSeriesItem, as was done in the example earlier. You can add data points with the add() method, or give all the data at once in a Collection with setData() or in the constructor.

The item hierarchy is defined with the setParent() method in the TreeSeriesItem instance or in the constructor. Parent argument can be either a String identifier or a TreeSeriesItem with a non-null ID. If no TreeSeriesItem with matching ID is found or if value is null then the parent will be rendered as a root item.

Polygons

A polygon can be used to draw any freeform filled or stroked shape in the Cartesian plane.

Polygons consist of connected data points. The DataSeries or ContainerSeries are usually the most meaningful data series types for polygon charts. In both cases, the x and y properties should be set.

charts polygon
Polygon combined with Scatter

Polygons have chart type POLYGON.

For example:

Chart chart = new Chart();
Configuration conf = chart.getConfiguration();
conf.setTitle("Height vs Weight");

XAxis xAxis = conf.getxAxis();
xAxis.setStartOnTick(true);
xAxis.setEndOnTick(true);
xAxis.setShowLastLabel(true);
xAxis.setTitle("Height (cm)");

YAxis yAxis = conf.getyAxis();
yAxis.setTitle("Weight (kg)");

PlotOptionsScatter optionsScatter = new PlotOptionsScatter();
DataSeries scatter = new DataSeries();
scatter.setPlotOptions(optionsScatter);
scatter.setName("Observations");

scatter.add(new DataSeriesItem(160, 67));
...
scatter.add(new DataSeriesItem(180, 75));
conf.addSeries(scatter);

DataSeries polygon = new DataSeries();
PlotOptionsPolygon optionsPolygon = new PlotOptionsPolygon();
optionsPolygon.setEnableMouseTracking(false);
polygon.setPlotOptions(optionsPolygon);
polygon.setName("Target");

polygon.add(new DataSeriesItem(153, 42));
polygon.add(new DataSeriesItem(149, 46));
...
polygon.add(new DataSeriesItem(173, 52));
polygon.add(new DataSeriesItem(166, 45));
conf.addSeries(polygon);

Plot Options

Polygon charts options can be configured in a PlotOptionsPolygon object, although it does not have any chart-type specific options.

Flags

Flags is a special chart type for annotating a series or the X axis with callout labels. Flags indicate interesting points or events on the series or axis. The flags are defined as items in a data series separate from the annotated series or axis.

charts flags
Flags placed on an axis and a series

Flags are normally used in a chart that has one or more normal data series.

Plot Options

The flags are defined in a series that has its chart type specified by setting its plot options as PlotOptionsFlags. In addition to the common plot options properties, flag charts also have the following properties:

shape

defines the shape of the marker. It can be one of FLAG, CIRCLEPIN, SQUAREPIN, or CALLOUT.

stackDistance

defines the vertical offset between flags on the same value in the same series. Defaults to 12.

onSeries

defines the ID of the series where the flags should be drawn on. If no ID is given, the flags are drawn on the X axis.

onKey

in chart types that have multiple keys (Y values) for a data point, the property defines on which key the flag is placed. Line and column series have only one key, y. In range, OHLC, and candlestick series, the flag can be placed on the open, high, low, or close key. Defaults to y.

Data

The data for flags series require x and title properties, but can also have text property indicating the tooltip text. The easiest way to set these properties is to use FlagItem.

Example

In the following, we annotate a time series as well as the axis with flags:

Chart chart = new Chart(ChartType.SPLINE);

Configuration configuration = chart.getConfiguration();
configuration.getTitle().setText("USD to EUR exchange rate");
configuration.getxAxis().setType(AxisType.DATETIME);

// A data series to annotate with flags
DataSeries dataSeries = new DataSeries();
dataSeries.setId("dataseries");
dataSeries.addData(new Number[][] { { 1434499200000l, 0.8821 },
        { 1434585600000l, 0.8802 }, { 1434672000000l, 0.8808 },
        { 1434844800000l, 0.8794 }, { 1434931200000l, 0.8818 },
        { 1435017600000l, 0.8952 }, { 1435104000000l, 0.8924 },
        { 1435190400000l, 0.8925 }, { 1435276800000l, 0.8955 } });

// Flags on the data series
DataSeries flagsOnSeries = new DataSeries();
flagsOnSeries.setName("Flags on series");
PlotOptionsFlags plotOptionsFlags = new PlotOptionsFlags();
plotOptionsFlags.setShape(FlagShape.SQUAREPIN);
plotOptionsFlags.setOnSeries("dataseries");
flagsOnSeries.setPlotOptions(plotOptionsFlags);
flagsOnSeries.add(new FlagItem(1434585600000l, "First Series Flag",
        "First Series Flag Tooltip Text"));
flagsOnSeries.add(new FlagItem(1435017600000l, "Second Series Flag"));

// Flags on the X axis
DataSeries flagsOnAxis = new DataSeries();
flagsOnAxis.setPlotOptions(new PlotOptionsFlags());
flagsOnAxis.setName("Flags on axis");
flagsOnAxis.add(new FlagItem(1434844800000l, "First Axis Flag",
        "First Axis Flag Tooltip Text"));
flagsOnAxis.add(new FlagItem(1435190400000l, "Second Axis Flag"));

configuration.setSeries(dataSeries, flagsOnSeries, flagsOnAxis);

OHLC and Candlestick Charts

An Open-High-Low-Close (OHLC) chart displays the change in price over a period of time. The OHLC charts have chart type OHLC. An OHLC chart consist of vertical lines, each having a horizontal tickmark both on the left and the right side. The top and bottom ends of the vertical line indicate the highest and lowest prices during the time period. The tickmark on the left side of the vertical line shows the opening price and the tickmark on the right side the closing price.

charts ohlc
OHLC Chart.

A candlestick chart is another way to visualize OHLC data. A candlestick has a body and two vertical lines, called wicks. The body represents the opening and closing prices. If the body is filled, the top edge of the body shows the opening price and the bottom edge shows the closing price. If the body is unfilled, the top edge shows the closing price and the bottom edge the opening price. In other words, if the body is filled, the opening price is higher than the closing price, and if not, lower. The upper wick represents the highest price during the time period and the lower wick represents the lowest price. A candlestick chart has chart type CANDLESTICK.

charts candlestick
Candlestick Chart.

To attach data to an OHLC or a candlestick chart, you need to use a DataSeries or a ContainerSeries. See "Chart Data" for more details. A data series for an OHLC chart must contain OhlcItem objects. An OhlcItem contains a date and the open, highest, lowest, and close price on that date.

Chart chart = new Chart(ChartType.OHLC);
chart.setTimeline(true);

Configuration configuration = chart.getConfiguration();
configuration.getTitle().setText("AAPL Stock Price");
DataSeries dataSeries = new DataSeries();
for (StockPrices.OhlcData data : StockPrices.fetchAaplOhlcPrice()) {
    OhlcItem item = new OhlcItem();
    item.setX(data.getDate());
    item.setLow(data.getLow());
    item.setHigh(data.getHigh());
    item.setClose(data.getClose());
    item.setOpen(data.getOpen());
    dataSeries.add(item);
}
configuration.setSeries(dataSeries);
chart.drawChart(configuration);

When using DataProviderSeries, you need to specify the functions used for retrieving OHLC properties: setX(), setOpen(), setHigh() setLow(), and setClose().

Chart chart = new Chart(ChartType.OHLC);
Configuration configuration = chart.getConfiguration();

// Create a DataProvider filled with stock price data
DataProvider<OhlcData, ?> dataProvider = initDataProvider();
// Wrap the container in a data series
DataProviderSeries<OhlcData> dataSeries = new DataProviderSeries<>(dataProvider);
dataSeries.setX(OhlcData::getDate);
dataSeries.setLow(OhlcData::getLow);
dataSeries.setHigh(OhlcData::getHigh);
dataSeries.setClose(OhlcData::getClose);
dataSeries.setOpen(OhlcData::getOpen);

PlotOptionsOhlc plotOptionsOhlc = new PlotOptionsOhlc();
plotOptionsOhlc.setTurboThreshold(0);
dataSeries.setPlotOptions(plotOptionsOhlc);

configuration.setSeries(dataSeries);

Typically the OHLC and candlestick charts contain a lot of data, so it is useful to use them with the timeline feature enabled. The timeline feature is described in "Timeline".

Plot Options

You can use a DataGrouping object to configure data grouping properties. You set it in the plot options with setDataGrouping(). If the data points in a series are so dense that the spacing between two or more points is less than value of the groupPixelWidth property in the DataGrouping, the points will be grouped into appropriate groups so that each group is more or less two pixels wide. The approximation property in DataGrouping specifies which data point value should represent the group. The possible values are: average, open, high, low, close, and sum.

Using setUpColor() and setUpLineColor() allow setting the fill and border colors of the candlestick that indicate rise in the values. The default colors are white.