Documentation

Documentation versions (currently viewingVaadin 24)

Chart Types

A list of chart types available and information on using and configuring them.

Charts come with over a dozen different 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

bullet

candlestick

column

columnrange

errorbar

flags

funnel

gauge

heatmap

line

ohlc

organization

pie

polygon

pyramid

scatter

solidgauge

spline

treemap

timeline

waterfall

xrange

Each chart type has its specific plot options and supports its specific collection of chart features. They also have specific requirements for the data series. Configuring Data Labels is common to all chart types. Configuring Markers is available for all chart types displaying point data.

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

Line and Spline Charts

Line charts connect a series of data points with lines. In basic line charts, the lines are straight, whereas 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

Line example

Open in a
new tab
Chart chart = new Chart(ChartType.LINE);

Configuration configuration = chart.getConfiguration();

configuration.setTitle("Solar Employment Growth by Sector, 2010-2016");
configuration.setSubTitle("Source: thesolarfoundation.com");

YAxis yAxis = configuration.getyAxis();
yAxis.setTitle("Number of Employees");

Legend legend = configuration.getLegend();
legend.setLayout(LayoutDirection.VERTICAL);
legend.setVerticalAlign(VerticalAlign.MIDDLE);
legend.setAlign(HorizontalAlign.RIGHT);

PlotOptionsSeries plotOptionsSeries = new PlotOptionsSeries();
plotOptionsSeries.setPointStart(2010);
configuration.setPlotOptions(plotOptionsSeries);

configuration.addSeries(new ListSeries("Installation", 43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175));
configuration.addSeries(new ListSeries("Manufacturing", 24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434));
configuration.addSeries(new ListSeries("Sales & Distribution", 11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387));
configuration.addSeries(new ListSeries("Project Development", null, null, 7988, 12169, 15112, 22452, 34400, 34227));
configuration.addSeries(new ListSeries("Other", 12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111));

Spline example

Open in a
new tab
Chart chart = new Chart(ChartType.SPLINE);

final Configuration configuration = chart.getConfiguration();
configuration.getTitle().setText("Random data");

XAxis xAxis = configuration.getxAxis();
xAxis.setType(AxisType.DATETIME);
xAxis.setTickPixelInterval(150);

YAxis yAxis = configuration.getyAxis();
yAxis.setTitle(new AxisTitle("Value"));

configuration.getTooltip().setEnabled(false);
configuration.getLegend().setEnabled(false);

final DataSeries series = new DataSeries();
series.setPlotOptions(new PlotOptionsSpline());
series.setName("Random data");
for (int i = -19; i <= 0; i++) {
    series.add(new DataSeriesItem(System.currentTimeMillis() + i * 1000, random.nextDouble()));
}

configuration.setSeries(series);

Area Charts

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

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 "RangeSeries", 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, whereas Stacking.PERCENT handles them as proportions.

See Data Point Markers for plot options for markers.

Area example

Open in a
new tab
Chart chart = new Chart(ChartType.AREA);

final Configuration configuration = chart.getConfiguration();

configuration.setTitle("Historic and Estimated Worldwide Population Growth by Region");
configuration.setSubTitle("Source: Wikipedia.org");

XAxis xAxis = configuration.getxAxis();
xAxis.setCategories("1750", "1800", "1850", "1900", "1950", "1999", "2050");
xAxis.setTickmarkPlacement(TickmarkPlacement.ON);

YAxis yAxis = configuration.getyAxis();
yAxis.setTitle("Billions");
yAxis.getLabels().setFormatter("function () { return this.value / 1000;}");

configuration.getTooltip().setValueSuffix(" millions");

PlotOptionsArea plotOptionsArea = new PlotOptionsArea();
plotOptionsArea.setStacking(Stacking.NORMAL);
configuration.setPlotOptions(plotOptionsArea);

configuration.addSeries(new ListSeries("Asia", 502, 635, 809, 947, 1402, 3634, 5268));
configuration.addSeries(new ListSeries("Africa", 106, 107, 111, 133, 221, 767, 1766));
configuration.addSeries(new ListSeries("Europe", 163, 203, 276, 408, 547, 729, 628));
configuration.addSeries(new ListSeries("America", 18, 31, 54, 156, 339, 818, 1201));
configuration.addSeries(new ListSeries("Oceania", 2, 2, 2, 6, 13, 30, 46));

Area Spline example

Open in a
new tab
Chart chart = new Chart(ChartType.AREASPLINE);
Configuration conf = chart.getConfiguration();

conf.setTitle(new Title("Average fruit consumption during one week"));

Legend legend = new Legend();
legend.setLayout(LayoutDirection.VERTICAL);
legend.setAlign(HorizontalAlign.LEFT);
legend.setFloating(true);
legend.setVerticalAlign(VerticalAlign.TOP);
legend.setX(150);
legend.setY(100);
conf.setLegend(legend);

XAxis xAxis = new XAxis();
xAxis.setCategories(new String[] { "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday", "Sunday" });
PlotBand plotBand = new PlotBand(4.5, 6.5, new SolidColor(0, 0, 0, 0.05));
plotBand.setZIndex(1);
xAxis.setPlotBands(plotBand);
conf.addxAxis(xAxis);

YAxis yAxis = new YAxis();
yAxis.setTitle(new AxisTitle("Fruit units"));
conf.addyAxis(yAxis);

Tooltip tooltip = new Tooltip();
// Customize tooltip formatting
tooltip.setShared(true);
tooltip.setValueSuffix(" units");
conf.setTooltip(tooltip);

PlotOptionsArea plotOptions = new PlotOptionsArea();
conf.setPlotOptions(plotOptions);

ListSeries o = new ListSeries("John", 3, 4, 3, 5, 4, 10);
// You can also add values separately
o.addData(12);
conf.addSeries(o);
conf.addSeries(new ListSeries("Jane", 1, 3, 4, 3, 3, 5, 4));

Area Range example

Open in a
new tab
Chart chart = new Chart(ChartType.AREARANGE);

Configuration conf = chart.getConfiguration();

conf.setTitle("Temperature variation by day");

conf.getxAxis().setType(AxisType.DATETIME);
conf.getxAxis().setCrosshair(new Crosshair());

Tooltip tooltip = new Tooltip();
tooltip.setShared(true);
tooltip.setValueSuffix("°C");
conf.setTooltip(tooltip);

RangeSeries data = new RangeSeries("Temperatures", getRawData());

conf.setSeries(data);

chart.setTimeline(true);

Area Spline Range example

Open in a
new tab
Chart chart = new Chart(ChartType.AREASPLINERANGE);

Configuration configuration = chart.getConfiguration();
configuration.getTitle().setText("Temperature variation by day");

Tooltip tooltip = configuration.getTooltip();
tooltip.setValueSuffix("°C");

DataSeries dataSeries = new DataSeries("Temperatures");
for (Number[] data : getRawData()) {
    dataSeries.add(new DataSeriesItem(data[0], data[1], data[2]));
}
configuration.setSeries(dataSeries);

chart.setTimeline(true);

Column and Bar Charts

Column and bar charts illustrate values as vertical or horizontal bars, respectively. The two chart types are essentially equivalent, 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 to define 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 of the plot options.

Column example

Open in a
new tab
Chart chart = new Chart(ChartType.COLUMN);

Configuration configuration = chart.getConfiguration();
configuration.setTitle("Monthly Average Rainfall");
configuration.setSubTitle("Source: WorldClimate.com");

configuration.addSeries(new ListSeries("Tokyo", 49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4));
configuration.addSeries(new ListSeries("New York", 83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3));
configuration.addSeries(new ListSeries("London", 48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2));
configuration.addSeries(new ListSeries("Berlin", 42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1));

XAxis x = new XAxis();
x.setCrosshair(new Crosshair());
x.setCategories("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
        "Sep", "Oct", "Nov", "Dec");
configuration.addxAxis(x);

YAxis y = new YAxis();
y.setMin(0);
y.setTitle("Rainfall (mm)");
configuration.addyAxis(y);

Tooltip tooltip = new Tooltip();
tooltip.setShared(true);
configuration.setTooltip(tooltip);

Column Range example

Open in a
new tab
Chart chart = new Chart(ChartType.COLUMNRANGE);

Configuration conf = chart.getConfiguration();

conf.setTitle("Temperature variation by day");

conf.getxAxis().setType(AxisType.DATETIME);
conf.getxAxis().setCrosshair(new Crosshair());

Tooltip tooltip = new Tooltip();
tooltip.setShared(true);
tooltip.setValueSuffix("°C");
conf.setTooltip(tooltip);

RangeSeries data = new RangeSeries("Temperatures", getRawData());

conf.setSeries(data);

Bar example

Open in a
new tab
Chart chart = new Chart(ChartType.BAR);

Configuration configuration = chart.getConfiguration();
configuration.setTitle("Historic World Population by Region");
configuration.setSubTitle("Source: <a href=\"https://en.wikipedia.org/wiki/World_population\">Wikipedia.org</a>");

configuration.addSeries(new ListSeries("Year 1800", 107, 31, 635, 203, 2));
configuration.addSeries(new ListSeries("Year 1900", 133, 156, 947, 408, 6));
configuration.addSeries(new ListSeries("Year 2000", 814, 841, 3714, 727, 31));
configuration.addSeries(new ListSeries("Year 2016", 1216, 1001, 4436, 738, 40));

XAxis x = new XAxis();
x.setCategories("Africa", "America", "Asia", "Europe", "Oceania");
configuration.addxAxis(x);

YAxis y = new YAxis();
y.setMin(0);
AxisTitle yTitle = new AxisTitle();
yTitle.setText("Population (millions)");
yTitle.setAlign(VerticalAlign.HIGH);
y.setTitle(yTitle);
configuration.addyAxis(y);

Tooltip tooltip = new Tooltip();
tooltip.setValueSuffix(" millions");
configuration.setTooltip(tooltip);

PlotOptionsBar plotOptions = new PlotOptionsBar();
DataLabels dataLabels = new DataLabels();
dataLabels.setEnabled(true);
plotOptions.setDataLabels(dataLabels);
configuration.setPlotOptions(plotOptions);

Error Bars

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

Although error bars are technically 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);

// 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));
...

// Need to be used for series to be recognized as error bar
PlotOptionsErrorbar barOptions = new PlotOptionsErrorbar();
errors.setPlotOptions(barOptions);

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

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. See the API documentation for details of the plot options.

Note
Although most visual styles are defined in CSS, some options, such as whiskerLength, are set through the Java API.

Error Bar example

Open in a
new tab
Chart chart = new Chart(ChartType.ERRORBAR);

Configuration configuration = chart.getConfiguration();
configuration.setTitle("Monthly Rainfall");

XAxis x = new XAxis();
x.setCategories("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
        "Sep", "Oct", "Nov", "Dec");
configuration.addxAxis(x);

YAxis y = new YAxis();
Labels yLabels = new Labels();
yLabels.setFormat("{value} mm");
y.setLabels(yLabels);
y.setTitle("Rainfall");
configuration.addyAxis(y);

Tooltip tooltip = new Tooltip();
tooltip.setShared(true);
configuration.setTooltip(tooltip);

Series rainfall = new ListSeries("Rainfall",
        49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6,
        148.5, 216.4, 194.1, 95.6, 54.4);
PlotOptionsColumn rainfallOptions = new PlotOptionsColumn();
SeriesTooltip rainfallTooltip = new SeriesTooltip();
rainfallTooltip.setPointFormat(
        "<span style=\"font-weight: bold; color: {series.color}\">" +
            "{series.name}</span>: <b>{point.y:.1f} mm</b> ");
rainfallOptions.setTooltip(rainfallTooltip);
rainfall.setPlotOptions(rainfallOptions);
configuration.addSeries(rainfall);

Series error = new RangeSeries("Rainfall error",
        new Number[] {48, 51},
        new Number[] {68, 73},
        new Number[] {92, 110},
        new Number[] {128, 136},
        new Number[] {140, 150},
        new Number[] {171, 179},
        new Number[] {135, 143},
        new Number[] {142, 149},
        new Number[] {204, 220},
        new Number[] {189, 199},
        new Number[] {95, 110},
        new Number[] {52, 56});
PlotOptionsErrorbar errorOptions = new PlotOptionsErrorbar();
SeriesTooltip errorTooltip = new SeriesTooltip();
errorTooltip.setPointFormat(
        "(error range: {point.low}-{point.high} mm)<br/>");
errorOptions.setTooltip(errorTooltip);
error.setPlotOptions(errorOptions);
configuration.addSeries(error);

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 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 only one data series, so it’s meaningful to disable the legend.

Chart chart = new Chart(ChartType.BOXPLOT);

// 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 more generic PlotOptionsErrorBar.

For example:

// Set median line color and thickness
PlotOptionsBoxplot plotOptions = new PlotOptionsBoxplot();
plotOptions.setWhiskerLength("80%");
conf.setPlotOptions(plotOptions);

Data Model

As the data points in box plots have five different values instead of the usual one, they require you to use 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);

Box Plot example

Open in a
new tab
Chart chart = new Chart(ChartType.BOXPLOT);

chart.getConfiguration().setTitle("Box Plot Example");

Legend legend = new Legend();
legend.setEnabled(true);
chart.getConfiguration().setLegend(legend);

XAxis xaxis = chart.getConfiguration().getxAxis();
xaxis.setTitle("Experiment No.");
xaxis.setCategories("1", "2", "3", "4", "5");

YAxis yAxis = chart.getConfiguration().getyAxis();
yAxis.setTitle("Observations");

PlotLine plotLine = new PlotLine();
plotLine.setValue(932);
plotLine.setZIndex(0);
Label label = new Label("Theoretical mean: 932");
label.setAlign(HorizontalAlign.CENTER);
plotLine.setLabel(label);
yAxis.setPlotLines(plotLine);

final DataSeries observations = new DataSeries();
observations.setName("Observations");

// Add PlotBoxItems contain all fields relevant for plot box chart
observations.add(new BoxPlotItem(760, 801, 848, 895, 965));

// Example with no arg constructor
BoxPlotItem plotBoxItem = new BoxPlotItem();
plotBoxItem.setLow(733);
plotBoxItem.setLowerQuartile(853);
plotBoxItem.setMedian(939);
plotBoxItem.setUpperQuartile(980);
plotBoxItem.setHigh(1080);
observations.add(plotBoxItem);

observations.add(new BoxPlotItem(714, 762, 817, 870, 918));
observations.add(new BoxPlotItem(724, 802, 806, 871, 950));
observations.add(new BoxPlotItem(834, 836, 864, 882, 910));
PlotOptionsBoxplot plotOptions = new PlotOptionsBoxplot();
SeriesTooltip observationsTooltip = new SeriesTooltip();
observationsTooltip.setHeaderFormat("<em>Experiment No {point.key}</em><br/>");
plotOptions.setTooltip(observationsTooltip);
observations.setPlotOptions(plotOptions);
chart.getConfiguration().addSeries(observations);

final DataSeries outlier = new DataSeries();
outlier.setName("Outlier");

outlier.add(new DataSeriesItem(0, 644));
outlier.add(new DataSeriesItem(4, 718));
outlier.add(new DataSeriesItem(4, 951));
outlier.add(new DataSeriesItem(4, 969));

PlotOptionsScatter outlierOptions = new PlotOptionsScatter();
SeriesTooltip outlierTooltip = new SeriesTooltip();
outlierTooltip.setPointFormat("Observation: {point.y}");
outlierOptions.setTooltip(outlierTooltip);
outlier.setPlotOptions(outlierOptions);

chart.getConfiguration().addSeries(outlier);

Scatter Charts

Scatter charts display a set of unconnected data points. The name refers to given X and Y coordinates, so the DataSeries or DataProviderSeries 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 doesn’t have any chart-type-specific options.

Chart chart = new Chart(ChartType.SCATTER);

// Modify the default configuration a bit
Configuration conf = chart.getConfiguration();
conf.setTitle("Random Sphere");
conf.getLegend().setEnabled(false); // Disable legend
conf.getxAxis().setTitle("X");
conf.getyAxis().setTitle("Y");
conf.getxAxis().setMax(1);
conf.getxAxis().setMin(-1);
conf.getyAxis().setMax(1);
conf.getyAxis().setMin(-1);

PlotOptionsScatter options = new PlotOptionsScatter();
// ... Give general 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);

    DataSeriesItem point = new DataSeriesItem(x,y);
    series.add(point);
}
conf.addSeries(series);

The result is shown in Scatter Chart.

Scatter example

Open in a
new tab
Chart chart = new Chart(ChartType.SCATTER);

Configuration configuration = chart.getConfiguration();

configuration.setTitle("Height Versus Weight of 507 Individuals by Gender");
configuration.setSubTitle("Source: Heinz  2003");

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

Legend legend = configuration.getLegend();
legend.setLayout(LayoutDirection.VERTICAL);
legend.setAlign(HorizontalAlign.LEFT);
legend.setVerticalAlign(VerticalAlign.TOP);
legend.setX(100);
legend.setY(70);
legend.setFloating(true);

PlotOptionsScatter plotOptionsScatter = new PlotOptionsScatter();
SeriesTooltip scatterTooltip = plotOptionsScatter.getTooltip();
scatterTooltip.setHeaderFormat("<b>{series.name}</b><br>\",\"pointFormat\":\"{point.x} cm, {point.y} kg");

DataSeries femaleSeries = new DataSeries();
femaleSeries.setName("Female");

PlotOptionsScatter femalePlotOptions = new PlotOptionsScatter();
femalePlotOptions.setClassName("femaleSeries");
femaleSeries.setPlotOptions(femalePlotOptions);

Number[][] femaleData = getFemaleData();
for (int i = 0; i < femaleData.length; i++) {
    DataSeriesItem item = new DataSeriesItem(femaleData[i][1], femaleData[i][0]);
    femaleSeries.add(item);
}
configuration.addSeries(femaleSeries);

DataSeries maleSeries = new DataSeries();
maleSeries.setName("Male");

PlotOptionsScatter malePlotOptions = new PlotOptionsScatter();
malePlotOptions.setClassName("maleSeries");
maleSeries.setPlotOptions(malePlotOptions);

Number[][] maleData = getMaleData();
for (int i = 0; i < maleData.length; i++) {
    DataSeriesItem item = new DataSeriesItem(maleData[i][1], maleData[i][0]);
    maleSeries.add(item);
}
configuration.addSeries(maleSeries);

Bubble Charts

Bubble charts are a special type of scatter chart for representing three-dimensional data points with different point sizes. Scatter Charts demonstrated the same purpose, but 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, similarly as 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 the 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 this by taking the square root of the Z values.

// Create a bubble chart
Chart chart = new Chart(ChartType.BUBBLE);

// Modify the default configuration a bit
Configuration conf = chart.getConfiguration();
conf.setTitle("Sugar and fat intake per country");
conf.setSubTitle("Source: <a href=\"http://www.euromonitor.com/\">Euromonitor</a> and <a href=\"https://data.oecd.org/\">OECD</a>");
conf.getLegend().setEnabled(false); // Disable legend
conf.getTooltip().setHeaderFormat("{point.country}");
conf.getTooltip().setPointFormat("Obesity (adults): {point.z}%");

PlotOptionsBubble plotOptions = new PlotOptionsBubble();
DataLabels chartLabels = new DataLabels();
chartLabels.setEnabled(true);
chartLabels.setFormat("{point.name}");
plotOptions.setDataLabels(chartLabels);
conf.setPlotOptions(plotOptions);

public static class MyDataSeriesItem extends DataSeriesItem3d {
  private String country;

  public MyDataSeriesItem(Number x, Number y, Number z, String name, String country) {
    super(x, y, z);
    setName(name);
    this.country = country;
  }

  public String getCountry() {
    return country;
  }
}

DataSeries series = new DataSeries("Countries");
series.add(new MyDataSeriesItem(95.0, 95.0, 13.8, "BE", "Belgium"));
series.add(new MyDataSeriesItem(86.5, 102.9, 14.7, "DE", "Germany"));
series.add(new MyDataSeriesItem(80.8, 91.5, 15.8, "FI", "Finland"));
...

conf.addSeries(series);

// Set the category labels on the axis correspondingly
XAxis xaxis = new XAxis();
xaxis.setTitle("Daily fat intake");
xaxis.getLabels().setFormat("{value} gr");
PlotLine xPlotLine = new PlotLine();
xPlotLine.setValue(65);
Label xLabel = new Label("Safe fat intake 65g/day");
xLabel.setRotation(0);
xLabel.setY(15);
xPlotLine.setLabel(xLabel);
xaxis.setPlotLines(xPlotLine);
conf.addxAxis(xaxis);

// Set the Y axis title
YAxis yaxis = new YAxis();
yaxis.setMax(160);
yaxis.setTitle("Daily sugar intake");
yaxis.getLabels().setFormat("{value} gr");
yaxis.setStartOnTick(false);
yaxis.setEndOnTick(false);
PlotLine yPlotLine = new PlotLine();
yPlotLine.setValue(50);
Label yLabel = new Label("Safe sugar intake 50g/day");
yLabel.setX(-10);
yLabel.setAlign(HorizontalAlign.RIGHT);
yPlotLine.setLabel(yLabel);
yaxis.setPlotLines(yPlotLine);
conf.addyAxis(yaxis);

Bubble example

Open in a
new tab
Chart chart = new Chart(ChartType.BUBBLE);

Configuration conf = chart.getConfiguration();
conf.setTitle((String) null);

DataSeries dataSeries = new DataSeries("All bubbles shown");
dataSeries.add(new DataSeriesItem3d(9, 81, 13));
dataSeries.add(new DataSeriesItem3d(98, 5, 39));
dataSeries.add(new DataSeriesItem3d(51, 50, 23));
dataSeries.add(new DataSeriesItem3d(41, 22, -36));
dataSeries.add(new DataSeriesItem3d(58, 24, -30));
dataSeries.add(new DataSeriesItem3d(78, 37, -16));
dataSeries.add(new DataSeriesItem3d(55, 56, 3));
dataSeries.add(new DataSeriesItem3d(18, 45, 20));
dataSeries.add(new DataSeriesItem3d(42, 44, -22));
dataSeries.add(new DataSeriesItem3d(3, 52, 9));
dataSeries.add(new DataSeriesItem3d(31, 18, 47));
dataSeries.add(new DataSeriesItem3d(79, 91, 13));
dataSeries.add(new DataSeriesItem3d(93, 23, -27));
dataSeries.add(new DataSeriesItem3d(44, 83, -28));

PlotOptionsBubble opts = new PlotOptionsBubble();
opts.setMaxSize("120");
opts.setMinSize("3");

conf.setPlotOptions(opts);

conf.addSeries(dataSeries);

DataSeries dataSeries2 = new DataSeries("Negative bubbles hidden");
dataSeries2.add(new DataSeriesItem3d(13, 30, 10));
dataSeries2.add(new DataSeriesItem3d(23, 20, -10));
dataSeries2.add(new DataSeriesItem3d(53, 40, 10));

opts = new PlotOptionsBubble();
opts.setDisplayNegative(false);
dataSeries2.setPlotOptions(opts);

conf.addSeries(dataSeries2);

Bullet Charts

Bullet charts display a value and a target value. They require the use of DataSeriesItemBullet.

Bullet Chart shows a configured bullet chart.

charts bullet
Bullet Chart

The chart type of a bullet chart is ChartType.BULLET. Its options can be configured in a PlotOptionsBullet object.

// Create a bullet chart
Chart chart = new Chart(ChartType.BULLET);
chart.setHeight("115px");

// Modify the default configuration
Configuration conf = chart.getConfiguration();
conf.setTitle("2020 YTD");
conf.getChart().setInverted(true);
conf.getLegend().setEnabled(false);
conf.getTooltip().setPointFormat(
        "<b>{point.y}</b> (with target at {point.target})");

// Add data
PlotOptionsBullet options = new PlotOptionsBullet();
options.setPointPadding(0.25);
options.setBorderWidth(0);
options.setColor(SolidColor.BLACK);
options.getTargetOptions().setWidth("200%");
DataSeries series = new DataSeries();
series.add(new DataSeriesItemBullet(275, 250));
series.setPlotOptions(options);
conf.addSeries(series);

// Configure the axes
YAxis yAxis = conf.getyAxis();
yAxis.setGridLineWidth(0);
yAxis.setTitle("");
yAxis.addPlotBand(new PlotBand(0, 150, new SolidColor("#666666")));
yAxis.addPlotBand(new PlotBand(150, 225, new SolidColor("#999999")));
yAxis.addPlotBand(new PlotBand(225, 9e9, new SolidColor("#bbbbbb")));
conf.getxAxis().addCategory(
        "<span style=\"font-size: 13px; font-weight: bold;\">Revenue</span><br/>U.S. $ (1,000s)");

Bullet example

Open in a
new tab
Chart chart = new Chart(ChartType.BULLET);

Configuration conf = chart.getConfiguration();
conf.getChart().setInverted(true);
conf.getChart().setMarginLeft(135);
conf.getLegend().setEnabled(false);
YAxis yAxis = conf.getyAxis();
yAxis.setGridLineWidth(0);
yAxis.setTitle("");
yAxis.addPlotBand(new PlotBand(0, 150,
        new SolidColor("#666666")));
yAxis.addPlotBand(new PlotBand(150, 225,
        new SolidColor("#999999")));
yAxis.addPlotBand(new PlotBand(225, 9e9,
        new SolidColor("#bbbbbb")));
conf.getxAxis().addCategory("<span style=\"font-size: 13px; font-weight: bold;\">Revenue</span><br/>U.S. $ (1,000s)");
conf.getTooltip().setPointFormat("<b>{point.y}</b> (with target at {point.target})");
PlotOptionsBullet options = new PlotOptionsBullet();
options.setPointPadding(0.25);
options.setBorderWidth(0);
options.setColor(SolidColor.BLACK);
options.getTargetOptions().setWidth("200%");
conf.setExporting(false);
DataSeries series = new DataSeries();
series.add(new DataSeriesItemBullet(275, 250));
series.setPlotOptions(options);
conf.addSeries(series);

Organization Charts

Organization charts are used to visualize parent/child relationships between nodes. They require the use of NodeSeries to add nodes and the hierarchical links between them.

The organization chart is enabled with ChartType.ORGANIZATION and you can make type-specific settings in the PlotOptionsOrganization object, as described later.

Chart chart = new Chart(ChartType.ORGANIZATION);
Configuration conf = chart.getConfiguration();
conf.getChart().setInverted(true);
conf.getChart().setHeight("500px");
conf.getTooltip().setOutside(true);
conf.setTitle("Acme organization chart");
...

Organization Chart shows a configured organization chart.

charts organization
Organization Chart

Plot Options

The chart-specific options of an organization chart are configured with a PlotOptionsOrganization.

PlotOptionsOrganization plotOptions = new PlotOptionsOrganization();
plotOptions.setColorByPoint(false);
plotOptions.setColor(new SolidColor("#007ad0"));

//Special color for first level
Level level0 = new Level();
level0.setLevel(0);
level0.setColor(new SolidColor("#99AED3"));
plotOptions.addLevel(level0);
conf.setPlotOptions(plotOptions);

Colors can be defined for all the nodes in the chart, for each level or individually in each node, as described later.

Data Model

To visualize the nodes and the hierarchy between them, you need to create a NodeSeries, create all the Node instances, then add them as NodeSeriesItem.

NodeSeries provides a method NodeSeries.add(nodeFrom, nodeTo) that adds the node to the list and adds a link between nodeFrom and nodeTo.

NodeSeries series = new NodeSeries();
series.setName("Acme");
Node acme = new Node("Acme");
Node headOffice = new Node("Head Office");
Node labs = new Node("Labs");
Node coyoteBuilding = new Node("Coyote Building");
Node roadRunnerBuilding = new Node("Road Runner Building");
Node sales = new Node("Sales");
Node marketing = new Node("Marketing");
Node accounting = new Node("Accounting");
Node administration = new Node("Administration");
Node mdsOffice = new Node("MD's Office");

Node josephMiler = new Node("Joseph Miler");
josephMiler.setTitle("Head of Sales");
josephMiler.setLayout(NodeLayout.HANGING);

Node erikPerez = new Node("Erik Perez");
erikPerez.setTitle("Head of Marketing");
erikPerez.setLayout(NodeLayout.HANGING);

Node emilyFox = new Node("Emily Fox");
emilyFox.setTitle("Head of Accounting");

Node ewanHerbert = new Node("Ewan Herbert");
ewanHerbert.setTitle("Head of Admin");
ewanHerbert.setLayout(NodeLayout.HANGING);

Node kateKirby = new Node("Kate Kirby");
Node vaughnWhiting = new Node("Vaughn Whiting");
Node lisaWarner = new Node("Lisa Warner");
Node mollyDodd = new Node("Molly Dodd");
Node natashaKelly = new Node("Natasha Kelly");

//Set color for a specific Node
Node managingDirector = new Node("Sally Brown", "Sally Brown",
        "Managing Director");
managingDirector.setColor(new SolidColor("#E4B651"));

series.add(acme, headOffice);
series.add(acme, labs);
series.add(headOffice, coyoteBuilding);
series.add(headOffice, roadRunnerBuilding);
series.add(coyoteBuilding, sales);
series.add(coyoteBuilding, marketing);
series.add(coyoteBuilding, accounting);
series.add(roadRunnerBuilding, administration);
series.add(roadRunnerBuilding, mdsOffice);
series.add(sales, josephMiler);
series.add(marketing, erikPerez);
series.add(accounting, emilyFox);
series.add(administration, ewanHerbert);
series.add(josephMiler, kateKirby);
series.add(josephMiler, vaughnWhiting);
series.add(erikPerez, lisaWarner);
series.add(ewanHerbert, mollyDodd);
series.add(ewanHerbert, natashaKelly);
series.add(mdsOffice, managingDirector);
conf.addSeries(series);

Organization example

Open in a
new tab
Chart chart = new Chart(ChartType.ORGANIZATION);

Configuration conf = chart.getConfiguration();
conf.getChart().setInverted(true);
conf.getChart().setHeight("500px");
conf.getTooltip().setOutside(true);
conf.setTitle("Acme organization chart");

NodeSeries series = new NodeSeries();
series.setName("Acme");
Node acme = new Node("Acme");
Node headOffice = new Node("Head Office");
Node labs = new Node("Labs");
Node coyoteBuilding = new Node("Coyote Building");
Node roadRunnerBuilding = new Node("Road Runner Building");
Node sales = new Node("Sales");
Node marketing = new Node("Marketing");
Node accounting = new Node("Accounting");
Node administration = new Node("Administration");
Node mdsOffice = new Node("MD's Office");

Node josephMiler = new Node("Joseph Miler");
josephMiler.setTitle("Head of Sales");
josephMiler.setLayout(NodeLayout.HANGING);

Node erikPerez = new Node("Erik Perez");
erikPerez.setTitle("Head of Marketing");
erikPerez.setLayout(NodeLayout.HANGING);

Node emilyFox = new Node("Emily Fox");
emilyFox.setTitle("Head of Accounting");

Node ewanHerbert = new Node("Ewan Herbert");
ewanHerbert.setTitle("Head of Admin");
ewanHerbert.setLayout(NodeLayout.HANGING);

Node kateKirby = new Node("Kate Kirby");
Node vaughnWhiting = new Node("Vaughn Whiting");
Node lisaWarner = new Node("Lisa Warner");
Node mollyDodd = new Node("Molly Dodd");
Node natashaKelly = new Node("Natasha Kelly");

Node managingDirector = new Node("Sally Brown", "Sally Brown",
        "Managing Director");
managingDirector.setColor(new SolidColor("#E4B651"));

series.add(acme, headOffice);
series.add(acme, labs);
series.add(headOffice, coyoteBuilding);
series.add(headOffice, roadRunnerBuilding);
series.add(coyoteBuilding, sales);
series.add(coyoteBuilding, marketing);
series.add(coyoteBuilding, accounting);
series.add(roadRunnerBuilding, administration);
series.add(roadRunnerBuilding, mdsOffice);
series.add(sales, josephMiler);
series.add(marketing, erikPerez);
series.add(accounting, emilyFox);
series.add(administration, ewanHerbert);
series.add(josephMiler, kateKirby);
series.add(josephMiler, vaughnWhiting);
series.add(erikPerez, lisaWarner);
series.add(ewanHerbert, mollyDodd);
series.add(ewanHerbert, natashaKelly);
series.add(mdsOffice, managingDirector);

PlotOptionsOrganization plotOptions = new PlotOptionsOrganization();
plotOptions.setColorByPoint(false);
plotOptions.setColor(new SolidColor("#007ad0"));
DataLabels dataLabels = new DataLabels();
dataLabels.setColor(SolidColor.BLACK);
plotOptions.setDataLabels(dataLabels);
plotOptions.setBorderColor(SolidColor.WHITE);

Level level0 = new Level();
level0.setLevel(0);
level0.setColor(new SolidColor("#99AED3"));

Level level1 = new Level();
level1.setLevel(1);
level1.setColor(new SolidColor("#CCE6C3"));

Level level2 = new Level();
level2.setLevel(2);
level2.setColor(new SolidColor("#E1F39D"));

Level level3 = new Level();
level3.setLevel(3);
level3.setColor(new SolidColor("#CCE6C3"));

Level level4 = new Level();
level4.setLevel(4);
level4.setColor(new SolidColor("#CABEDC"));

Level level5 = new Level();
level5.setLevel(5);
level5.setColor(new SolidColor("#CABDD4"));

plotOptions.addLevel(level0);
plotOptions.addLevel(level1);
plotOptions.addLevel(level2);
plotOptions.addLevel(level3);
plotOptions.addLevel(level4);
series.setPlotOptions(plotOptions);
conf.addSeries(series);

Pie Charts

A pie chart illustrates data values as sectors whose size is proportional to the sum of all the values. A pie chart is enabled with ChartType.PIE. You can make type-specific settings in the PlotOptionsPie object, as described later.

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

Pie Chart shows a configured 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 an inner size greater than zero is a "doughnut". The inner size can be expressed either as pixels or as a relative percentage of the chart area with a string (such as "60%"). See the later section on doughnuts.

size

The size of the pie can be expressed either as pixels or 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 as either numbers of pixels or 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. DataSeries or ContainerSeries, which allow the data points to be labeled, 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’s shown as slightly cut away from the pie.

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

Pie example

Open in a
new tab
Chart chart = new Chart(ChartType.PIE);

Configuration conf = chart.getConfiguration();

conf.setTitle("Browser market shares in January, 2018");

Tooltip tooltip = new Tooltip();
tooltip.setValueDecimals(1);
conf.setTooltip(tooltip);

PlotOptionsPie plotOptions = new PlotOptionsPie();
plotOptions.setAllowPointSelect(true);
plotOptions.setCursor(Cursor.POINTER);
plotOptions.setShowInLegend(true);
conf.setPlotOptions(plotOptions);

DataSeries series = new DataSeries();
DataSeriesItem chrome = new DataSeriesItem("Chrome", 61.41);
chrome.setSliced(true);
chrome.setSelected(true);
series.add(chrome);
series.add(new DataSeriesItem("Internet Explorer", 11.84));
series.add(new DataSeriesItem("Firefox", 10.85));
series.add(new DataSeriesItem("Edge", 4.67));
series.add(new DataSeriesItem("Safari", 4.18));
series.add(new DataSeriesItem("Sogou Explorer", 1.64));
series.add(new DataSeriesItem("Opera", 6.2));
series.add(new DataSeriesItem("QQ", 1.2));
series.add(new DataSeriesItem("Others", 2.61));
conf.setSeries(series);
chart.setVisibilityTogglingDisabled(true);

Doughnut Charts

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

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

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

// 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 Doughnut Chart.

charts donut
Overlaid Pie and Doughnut Chart

Gauges

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

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

Note
Gauge and solid gauge series shouldn’t be combined with series of other types.
Note
A bar series inverts the entire chart; combine with care.

Consider the following gauge:

Chart chart = new Chart(ChartType.GAUGE);

With the settings shown in the following sections, it is displayed 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 a Y-axis. You need to provide both a minimum and a maximum value for this.

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);

PlotBand green = new PlotBand(0, 60, null);
green.setClassName("green");

PlotBand yellow = new PlotBand(60, 80, null);
yellow.setClassName("yellow");

PlotBand red = new PlotBand(80, 100, null);
red.setClassName("red");

yaxis.setPlotBands(green, yellow, red);

conf.addyAxis(yaxis);

You can make all kinds of other configuration settings to the axis. See the API documentation for all the available parameters.

Setting and Updating Gauge Data

A gauge displays only a single value, which you can define as a data series of length 1, for example 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.add(tf);

Button update = new Button("Update", (e) -> {
    Integer newValue = new Integer(tf.getValue());
    series.updatePoint(0, newValue);
});
layout.add(update);

Gauge example

Open in a
new tab
Chart chart = new Chart(ChartType.GAUGE);

final Configuration configuration = chart.getConfiguration();
configuration.setTitle("Speedometer");
configuration.getChart().setWidth(500);

Pane pane = configuration.getPane();
pane.setStartAngle(-150);
pane.setEndAngle(150);

YAxis yAxis = new YAxis();
yAxis.setTitle("km/h");
yAxis.setMin(0);
yAxis.setMax(200);
yAxis.setTickLength(10);
yAxis.setTickPixelInterval(30);
yAxis.setTickPosition(TickPosition.INSIDE);
yAxis.setMinorTickLength(10);
yAxis.setMinorTickInterval("auto");
yAxis.setMinorTickPosition(TickPosition.INSIDE);

Labels labels = new Labels();
labels.setStep(2);
labels.setRotation("auto");
yAxis.setLabels(labels);

PlotBand[] bands = new PlotBand[3];
bands[0] = new PlotBand();
bands[0].setFrom(0);
bands[0].setTo(120);
bands[0].setClassName("band-0");
bands[1] = new PlotBand();
bands[1].setFrom(120);
bands[1].setTo(160);
bands[1].setClassName("band-1");
bands[2] = new PlotBand();
bands[2].setFrom(160);
bands[2].setTo(200);
bands[2].setClassName("band-2");
yAxis.setPlotBands(bands);

configuration.addyAxis(yAxis);

final ListSeries series = new ListSeries("Speed", 89);

PlotOptionsGauge plotOptionsGauge = new PlotOptionsGauge();
SeriesTooltip tooltip = new SeriesTooltip();
tooltip.setValueSuffix(" km/h");
plotOptionsGauge.setTooltip(tooltip);
series.setPlotOptions(plotOptionsGauge);

configuration.addSeries(series);

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 shown by a rotating arc with a solid color. The color of the indicator arc can be configured to change according to the value, using color stops.

Consider the following gauge:

Chart chart = new Chart(ChartType.SOLIDGAUGE);

With the settings shown in the following sections, it is displayed as in A Solid Gauge.

charts solidgauge
A Solid Gauge

Although 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; enlarging it allows better positioning of the tick labels.

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. As a minimum, you need to set the shape as either " arc`" or " [literal]solid`". You also typically want to set background color and inner and outer radius.

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

Axis Configuration

A gauge has only a 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

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

You can make all kinds of other configuration settings on the axis. See the API documentation for all the available parameters.

Plot Options

Solid gauges don’t 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 displays only a single value, which you can define as a data series of length 1, as in the following example:

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.add(tf);

Button update = new Button("Update", (e) -> {
    Integer newValue = new Integer(tf.getValue());
    series.updatePoint(0, newValue);
});
layout.add(update);

Solid Gauge example

Open in a
new tab
Chart chart = new Chart(ChartType.SOLIDGAUGE);

Configuration configuration = chart.getConfiguration();

Pane pane = configuration.getPane();
pane.setCenter(new String[] {"50%", "50%"});
pane.setStartAngle(-90);
pane.setEndAngle(90);

Background paneBackground = new Background();
paneBackground.setInnerRadius("60%");
paneBackground.setOuterRadius("100%");
paneBackground.setShape(BackgroundShape.ARC);
pane.setBackground(paneBackground);

YAxis yAxis = configuration.getyAxis();
yAxis.setTickAmount(2);
yAxis.setTitle("Speed");
yAxis.setMinorTickInterval("null");
yAxis.getTitle().setY(-50);
yAxis.getLabels().setY(16);
yAxis.setMin(0);
yAxis.setMax(200);


PlotOptionsSolidgauge plotOptionsSolidgauge = new PlotOptionsSolidgauge();

DataLabels dataLabels = plotOptionsSolidgauge.getDataLabels();
dataLabels.setY(5);
dataLabels.setUseHTML(true);

configuration.setPlotOptions(plotOptionsSolidgauge);

DataSeries series = new DataSeries("Speed");

DataSeriesItem item = new DataSeriesItem();
item.setY(80);
DataLabels dataLabelsSeries = new DataLabels();
dataLabelsSeries.setFormat("<div style=\"text-align:center\"><span style=\"font-size:25px;"
        + "color:black' + '\">{y}</span><br/>"
        + "<span style=\"font-size:12px;color:silver\">km/h</span></div>");

item.setDataLabels(dataLabelsSeries);

series.add(item);

configuration.addSeries(series);

Area and Column Range Charts

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

Consider the following example:

Chart chart = new Chart(ChartType.AREARANGE);

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

// Create the range series
// Source: http://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, and the same chart with a column range, are shown in Area and Column Range Chart.

charts arearange
Area and Column Range Chart

Area Range example

Open in a
new tab
Chart chart = new Chart(ChartType.AREARANGE);

Configuration conf = chart.getConfiguration();

conf.setTitle("Temperature variation by day");

conf.getxAxis().setType(AxisType.DATETIME);
conf.getxAxis().setCrosshair(new Crosshair());

Tooltip tooltip = new Tooltip();
tooltip.setShared(true);
tooltip.setValueSuffix("°C");
conf.setTooltip(tooltip);

RangeSeries data = new RangeSeries("Temperatures", getRawData());

conf.setSeries(data);

chart.setTimeline(true);

Column Range example

Open in a
new tab
Chart chart = new Chart(ChartType.COLUMNRANGE);

Configuration conf = chart.getConfiguration();

conf.setTitle("Temperature variation by day");

conf.getxAxis().setType(AxisType.DATETIME);
conf.getxAxis().setCrosshair(new Crosshair());

Tooltip tooltip = new Tooltip();
tooltip.setShared(true);
tooltip.setValueSuffix("°C");
conf.setTooltip(tooltip);

RangeSeries data = new RangeSeries("Temperatures", getRawData());

conf.setSeries(data);

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 the Y axis from the center of the circle to its rim. Polar chart isn’t a chart type in itself, but can be enabled for most chart types with setPolar(true) in the chart model parameters. All chart-type-specific features are usable with polar charts.

Charts allow 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 a full circle, so no angles for the pane need to be specified.

Note the style settings made in the axis in the following example:

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: http://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);

Polar example

Open in a
new tab
Chart chart = new Chart();

Configuration conf = chart.getConfiguration();
conf.getChart().setPolar(true);
conf.setTitle("Polar Chart");

Pane pane = new Pane(0, 360);
conf.addPane(pane);

XAxis xAxis = new XAxis();
xAxis.setTickInterval(45);
xAxis.setMin(0);
xAxis.setMax(360);
Labels labels = new Labels();
labels.setFormatter("function() {return this.value + '°';}");
xAxis.setLabels(labels);
YAxis yAxis = new YAxis();
yAxis.setMin(0);
conf.addxAxis(xAxis);
conf.addyAxis(yAxis);

PlotOptionsSeries series = new PlotOptionsSeries();
PlotOptionsColumn column = new PlotOptionsColumn();
series.setPointStart(0);
series.setPointInterval(45);
column.setPointPadding(0);
column.setGroupPadding(0);

conf.setPlotOptions(series, column);

ListSeries col = new ListSeries(8, 7, 6, 5, 4, 3, 2, 1);
ListSeries line = new ListSeries(1, 2, 3, 4, 5, 6, 7, 8);
ListSeries area = new ListSeries(1, 8, 2, 7, 3, 6, 4, 5);

col.setPlotOptions(new PlotOptionsColumn());
col.setName(ChartType.COLUMN.toString());

line.setPlotOptions(new PlotOptionsLine());
line.setName(ChartType.LINE.toString());

area.setPlotOptions(new PlotOptionsArea());
area.setName(ChartType.AREA.toString());

conf.setSeries(col, line, area);

Funnel and Pyramid Charts

Funnel and pyramid charts are typically used to visualize stages in a sales process, 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 the width of the drawing area of the chart, and diminishes in size down to a funnel "neck" that continues as a column to the bottom. A pyramid diminishes from bottom to top and doesn’t 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. 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 and PlotOptionsFunnel, respectively.

On top of the 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 a 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 inverted from the normal direction, diminishing from the top to bottom. The default is false for funnel and true for pyramid.

Funnel example

Open in a
new tab
Chart chart = new Chart(ChartType.FUNNEL);

Configuration conf = chart.getConfiguration();
conf.setTitle("Sales funnel");
conf.getLegend().setEnabled(false);

PlotOptionsFunnel options = new PlotOptionsFunnel();
options.setReversed(false);
options.setNeckWidth("30%");
options.setNeckHeight("30%");

options.setWidth("70%");

DataLabelsFunnel dataLabels = new DataLabelsFunnel();
dataLabels.setFormat("<b>{point.name}</b> ({point.y:,.0f})");
options.setDataLabels(dataLabels);

DataSeries dataSeries = new DataSeries("Unique users");
dataSeries.add(new DataSeriesItem("Website visits", 15654));
dataSeries.add(new DataSeriesItem("Downloads", 4064));
dataSeries.add(new DataSeriesItem("Requested price list", 1987));
dataSeries.add(new DataSeriesItem("Invoice sent", 976));
dataSeries.add(new DataSeriesItem("Finalized", 846));


dataSeries.setPlotOptions(options);
conf.addSeries(dataSeries);

Pyramid example

Open in a
new tab
Chart chart = new Chart(ChartType.PYRAMID);
Configuration configuration = chart.getConfiguration();

configuration.setTitle("Sales pyramid");
configuration.getLegend().setEnabled(false);

PlotOptionsPyramid plotOptionsSeries = new PlotOptionsPyramid();
DataLabelsFunnel dataLabels = plotOptionsSeries.getDataLabels();
dataLabels.setEnabled(true);
dataLabels.setSoftConnector(true);
dataLabels.setFormat("<b>{point.name}</b> ({point.y:,.0f})");

plotOptionsSeries.setCenter("40%", "50%");
plotOptionsSeries.setWidth("60%");

configuration.setPlotOptions(plotOptionsSeries);

DataSeries series = new DataSeries("Unique users");

series.add(new DataSeriesItem("Website visits", 15654));
series.add(new DataSeriesItem("Downloads", 4064));
series.add(new DataSeriesItem("Requested price list", 1987));
series.add(new DataSeriesItem("Invoice sent", 976));
series.add(new DataSeriesItem("Finalized", 846));

configuration.addSeries(series);

Waterfall Charts

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

charts waterfall
Waterfall Charts

Waterfall charts have chart type WATERFALL.

For example:

Chart chart = new Chart(ChartType.WATERFALL);

DataSeries dataSeries = new DataSeries();

dataSeries.add(new DataSeriesItem("Start", 120000));
dataSeries.add(new DataSeriesItem("Product Revenue", 569000));
dataSeries.add(new DataSeriesItem("Service Revenue", 231000));
WaterFallSum positiveBalance = new WaterFallSum("Positive Balance");
positiveBalance.setIntermediate(true);
dataSeries.add(positiveBalance);

dataSeries.add(new DataSeriesItem("Fixed Costs", -342000));
dataSeries.add(new DataSeriesItem("Variable Costs", -233000));
WaterFallSum balance = new WaterFallSum("Balance");
dataSeries.add(balance);

PlotOptionsWaterfall opts = new PlotOptionsWaterfall();
DataLabels dataLabels = new DataLabels(true);
dataLabels.setVerticalAlign(VerticalAlign.TOP);
dataLabels.setY(-30);
dataLabels.setFormatter("function() { return this.y / 1000 + 'k'; }");
opts.setDataLabels(dataLabels);

dataSeries.setPlotOptions(opts);

Configuration configuration = chart.getConfiguration();
configuration.addSeries(dataSeries);
configuration.getxAxis().setType(AxisType.CATEGORY);
...

Waterfall charts can be styled by CSS using the following classes: .highcharts-waterfall-series, .highcharts-point, .highcharts-negative, .highcharts-sum, .highcharts-intermediate-sum.

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 positive values.

color

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

The following defines 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 consist 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);

Waterfall example

Open in a
new tab
Chart chart = new Chart(ChartType.WATERFALL);

DataSeries dataSeries = new DataSeries();

dataSeries.add(new DataSeriesItem("Start", 120000));
dataSeries.add(new DataSeriesItem("Product Revenue", 569000));
dataSeries.add(new DataSeriesItem("Service Revenue", 231000));
WaterFallSum positiveBalance = new WaterFallSum("Positive Balance");
positiveBalance.setIntermediate(true);
dataSeries.add(positiveBalance);

dataSeries.add(new DataSeriesItem("Fixed Costs", -342000));
dataSeries.add(new DataSeriesItem("Variable Costs", -233000));
WaterFallSum balance = new WaterFallSum("Balance");
dataSeries.add(balance);

PlotOptionsWaterfall opts = new PlotOptionsWaterfall();
DataLabels dataLabels = new DataLabels(true);
dataLabels.setVerticalAlign(VerticalAlign.TOP);
dataLabels.setY(-30);
dataLabels.setFormatter("function() { return this.y / 1000 + 'k'; }");
opts.setDataLabels(dataLabels);

dataSeries.setPlotOptions(opts);

Configuration configuration = chart.getConfiguration();
configuration.addSeries(dataSeries);
configuration.getxAxis().setType(AxisType.CATEGORY);

Timeline Charts

Timeline charts are used to visualize events on a time axis. They require the use of DataSeriesItemTimeline to set an X value, together with name, label and description for the event.

A ready Timeline chart is shown in Timeline Chart.

charts timeline
Timeline Chart

The chart type of a timeline chart is ChartType.TIMELINE. Its options can be configured in a PlotOptionsTimeline object.

// Create a timeline chart
Chart chart = new Chart(ChartType.TIMELINE);

// Modify the default configuration
Configuration conf = chart.getConfiguration();
conf.setTitle("Timeline of Space Exploration");
conf.setSubTitle(
        "Info source: <a href=\"https://en.wikipedia.org/wiki/Timeline_of_space_exploration\">www.wikipedia.org</a>");
conf.getTooltip().setEnabled(true);

// Add data
DataSeries series = new DataSeries();
series.add(new DataSeriesItemTimeline(getInstant(1951, 6, 22),
        "First dogs in space", "First dogs in space",
        "Dezik and Tsygan were the first dogs to make a sub-orbital flight on 22 July 1951. Both dogs were recovered unharmed after travelling to a maximum altitude of 110 km."));
series.add(new DataSeriesItemTimeline(getInstant(1957, 10, 4),
        "First artificial satellite", "First artificial satellite",
        "Sputnik 1 was the first artificial Earth satellite. The Soviet Union launched it into an elliptical low Earth orbit on 4 October 1957, orbiting for three weeks before its batteries died, then silently for two more months before falling back into the atmosphere."));
series.add(new DataSeriesItemTimeline(getInstant(1959, 1, 4),
        "First artificial satellite to reach the Moon",
        "First artificial satellite to reach the Moon",
        "Luna 1 was the first artificial satellite to reach the Moon vicinity and first artificial satellite in heliocentric orbit."));
series.add(new DataSeriesItemTimeline(getInstant(1961, 4, 12),
        "First human spaceflight", "First human spaceflight",
        "Yuri Gagarin was a Soviet pilot and cosmonaut. He became the first human to journey into outer space when his Vostok spacecraft completed one orbit of the Earth on 12 April 1961."));
series.add(new DataSeriesItemTimeline(getInstant(1966, 2, 3),
        "First soft landing on the Moon",
        "First soft landing on the Moon",
        "Yuri Gagarin was a Soviet pilot and cosmonaut. He became the first human to journey into outer space when his Vostok spacecraft completed one orbit of the Earth on 12 April 1961."));
series.add(new DataSeriesItemTimeline(getInstant(1969, 7, 20),
        "First human on the Moon", "First human on the Moon",
        "Apollo 11 was the spaceflight that landed the first two people on the Moon. Commander Neil Armstrong and lunar module pilot Buzz Aldrin, both American, landed the Apollo Lunar Module Eagle on July 20, 1969, at 20:17 UTC."));
series.add(new DataSeriesItemTimeline(getInstant(1971, 4, 19),
        "First space station", "First space station",
        "Salyut 1 was the first space station of any kind, launched into low Earth orbit by the Soviet Union on April 19, 1971. The Salyut program followed this with five more successful launches out of seven more stations."));
series.add(new DataSeriesItemTimeline(getInstant(1971, 12, 2),
        "First soft Mars landing", "First soft Mars landing",
        "Mars 3 was an unmanned space probe of the Soviet Mars program which spanned the years between 1960 and 1973. Mars 3 was launched May 28, 1971, nine days after its twin spacecraft Mars 2. The probes were identical robotic spacecraft launched by Proton-K rockets with a Blok D upper stage, each consisting of an orbiter and an attached lander."));
series.add(new DataSeriesItemTimeline(getInstant(1976, 4, 17),
        "Closest flyby of the Sun", "Closest flyby of the Sun",
        "Helios-A and Helios-B (also known as Helios 1 and Helios 2) are a pair of probes launched into heliocentric orbit for the purpose of studying solar processes. A joint venture of West Germany's space agency DFVLR (70 percent share) and NASA (30 percent), the probes were launched from Cape Canaveral Air Force Station, Florida."));
series.add(new DataSeriesItemTimeline(getInstant(1978, 12, 4),
        "First orbital exploration of Venus",
        "First orbital exploration of Venus",
        "The Pioneer Venus Orbiter entered orbit around Venus on December 4, 1978, and performed observations to characterize the atmosphere and surface of Venus. It continued to transmit data until October 1992."));
series.add(new DataSeriesItemTimeline(getInstant(1986, 2, 19),
        "First inhabited space station",
        "First inhabited space station",
        "Mir was a space station that operated in low Earth orbit from 1986 to 2001, operated by the Soviet Union and later by Russia. Mir was the first modular space station and was assembled in orbit from 1986 to 1996. It had a greater mass than any previous spacecraft."));
series.add(new DataSeriesItemTimeline(getInstant(1989, 8, 8),
        "First astrometric satellite", "First astrometric satellite",
        "Hipparcos was a scientific satellite of the European Space Agency (ESA), launched in 1989 and operated until 1993. It was the first space experiment devoted to precision astrometry, the accurate measurement of the positions of celestial objects on the sky."));
series.add(new DataSeriesItemTimeline(getInstant(1998, 11, 20),
        "First multinational space station",
        "First multinational space station",
        "The International Space Station (ISS) is a space station, or a habitable artificial satellite, in low Earth orbit. Its first component was launched into orbit in 1998, with the first long-term residents arriving in November 2000.[7] It has been inhabited continuously since that date."));

PlotOptionsTimeline options = new PlotOptionsTimeline();
options.getMarker().setSymbol(MarkerSymbolEnum.CIRCLE);
DataLabels labels = options.getDataLabels();
labels.setAllowOverlap(false);
labels.setFormat(
        "<span style=\"color:{point.color}\">● </span><span style=\"font-weight: bold;\" > {point.x:%d %b %Y}</span><br/>{point.label}");
series.setPlotOptions(options);
conf.addSeries(series);

// Configure the axes
conf.getxAxis().setVisible(false);
conf.getxAxis().setType(AxisType.DATETIME);
conf.getyAxis().setVisible(false);
// Helper method to create an Instant from year, month and day
private Instant getInstant(int year, int month, int dayOfMonth) {
    return LocalDate.of(year, month, dayOfMonth).atStartOfDay().toInstant(ZoneOffset.UTC);
}

Timeline example

Open in a
new tab
Chart chart = new Chart(ChartType.TIMELINE);

Configuration conf = chart.getConfiguration();
conf.getxAxis().setVisible(false);
conf.getyAxis().setVisible(false);
conf.setTitle("Timeline of Space Exploration");
conf.setSubTitle(
        "Info source: <a href=\"https://en.wikipedia.org/wiki/Timeline_of_space_exploration\">www.wikipedia.org</a>");
conf.getTooltip().setEnabled(true);

DataSeries series = new DataSeries();
series.add(new DataSeriesItemTimeline("First dogs",
        "1951: First dogs in space",
        "22 July 1951 First dogs in space (Dezik and Tsygan)"));
series.add(new DataSeriesItemTimeline("Sputnik 1",
        "1957: First artificial satellite",
        "4 October 1957 First artificial satellite. First signals from space."));
series.add(new DataSeriesItemTimeline("First human spaceflight",
        "1961: First human spaceflight (Yuri Gagarin)",
        "First human spaceflight (Yuri Gagarin), and the first human-crewed orbital flight"));
series.add(new DataSeriesItemTimeline("First human on the Moon",
        "1969: First human on the Moon",
        "First human on the Moon, and first space launch from a celestial body other than the Earth. First sample return from the Moon"));

conf.addSeries(series);

X-Range Charts

X-Range charts are used to visualize a range on the X axis. They require the use of DataSeriesItemXrange to set an initial X value and a final X2 value. Additionally, partialFillAmount can be set to show the percentage of the point to be filled.

A ready X-Range chart is shown in X-Range Chart.

charts xrange
X-Range Chart

The chart type of an X-Range chart is ChartType.XRANGE. Its options can be configured in a PlotOptionsXrange object.

// Create a xrange chart
Chart chart = new Chart(ChartType.XRANGE);

// Modify the default configuration
Configuration conf = chart.getConfiguration();
conf.setTitle("X-range");

// Add data
DataSeries series = new DataSeries();
series.setName("Project 1");
series.add(new DataSeriesItemXrange(getInstant(2014, 11, 21),
        getInstant(2014, 12, 2), 0, 0.25));
series.add(new DataSeriesItemXrange(getInstant(2014, 12, 2),
        getInstant(2014, 12, 5), 1));
series.add(new DataSeriesItemXrange(getInstant(2014, 12, 8),
        getInstant(2014, 12, 9), 2));
series.add(new DataSeriesItemXrange(getInstant(2014, 12, 9),
        getInstant(2014, 12, 19), 1));
series.add(new DataSeriesItemXrange(getInstant(2014, 12, 10),
        getInstant(2014, 12, 23), 2));
PlotOptionsXrange options = new PlotOptionsXrange();
options.setBorderColor(SolidColor.GRAY);
options.setPointWidth(20);
options.getDataLabels().setEnabled(true);
series.setPlotOptions(options);
conf.addSeries(series);

// Configure the axes
conf.getxAxis().setType(AxisType.DATETIME);
conf.getyAxis().setTitle("");
conf.getyAxis().setCategories("Prototyping", "Development", "Testing");
conf.getyAxis().setReversed(true);
// Helper method to create an Instant from year, month and day
private Instant getInstant(int year, int month, int dayOfMonth) {
    return LocalDate.of(year, month, dayOfMonth).atStartOfDay().toInstant(ZoneOffset.UTC);
}

X-Range example

Open in a
new tab
Chart chart = new Chart(ChartType.XRANGE);

Configuration conf = chart.getConfiguration();
conf.setTitle("X-range");
conf.getxAxis().setType(AxisType.DATETIME);
conf.getyAxis().setTitle("");
conf.getyAxis().setCategories("Prototyping", "Development", "Testing");
conf.getyAxis().setReversed(true);

DataSeries series = new DataSeries();
series.setName("Project 1");

series.add(new DataSeriesItemXrange(getInstant(2014, 11, 21),
        getInstant(2014, 12, 2), 0, 0.25));
series.add(new DataSeriesItemXrange(getInstant(2014, 12, 2),
        getInstant(2014, 12, 5), 1));
series.add(new DataSeriesItemXrange(getInstant(2014, 12, 8),
        getInstant(2014, 12, 9), 2));
series.add(new DataSeriesItemXrange(getInstant(2014, 12, 9),
        getInstant(2014, 12, 19), 1));
series.add(new DataSeriesItemXrange(getInstant(2014, 12, 10),
        getInstant(2014, 12, 23), 2));

PlotOptionsXrange options = new PlotOptionsXrange();
options.setBorderColor(SolidColor.GRAY);
options.setPointWidth(20);
options.getDataLabels().setEnabled(true);
series.setPlotOptions(options);
conf.addSeries(series);

Heat Maps

A heat map is a two-dimensional grid, where the color of a grid cell reflects 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 earlier example. 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 another data series type for a heat map, 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.

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’s faster to replace the data series and then call chart.drawChart().

Heat Map example

Open in a
new tab
Chart chart = new Chart(ChartType.HEATMAP);

Configuration config = chart.getConfiguration();
config.getChart().setMarginTop(40);
config.getChart().setMarginBottom(40);

config.getTitle().setText("Sales per employee per weekday");

config.getxAxis()
        .setCategories("Marta", "Mysia", "Misiek", "Maniek", "Miki",
                "Guillermo", "Jonatan", "Zdzisław", "Antoni", "Zygmunt");
config.getyAxis().setCategories("Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday");

config.getColorAxis().setMin(0);
config.getColorAxis().setMinColor(SolidColor.WHITE);
SolidColor lightBlue = new SolidColor(22, 118, 243);
config.getColorAxis().setMaxColor(lightBlue);

config.getLegend().setLayout(LayoutDirection.VERTICAL);
config.getLegend().setAlign(HorizontalAlign.RIGHT);
config.getLegend().setMargin(0);
config.getLegend().setVerticalAlign(VerticalAlign.TOP);
config.getLegend().setY(25);
config.getLegend().setSymbolHeight(320);

HeatSeries rs = new HeatSeries("Sales per employee", getRawData());

PlotOptionsHeatmap plotOptionsHeatmap = new PlotOptionsHeatmap();
plotOptionsHeatmap.setDataLabels(new DataLabels());
plotOptionsHeatmap.getDataLabels().setEnabled(true);

SeriesTooltip tooltip = new SeriesTooltip();
tooltip.setHeaderFormat("{series.name}<br/>");
tooltip.setPointFormat("Amount: <b>{point.value}</b> ");
plotOptionsHeatmap.setTooltip(tooltip);
config.setPlotOptions(plotOptionsHeatmap);

config.setSeries(rs);

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 represents the item value.

charts treemap
Tree Maps

Tree maps have chart type TREEMAP.

To create a Tree Map chart, you need to create a class that extends TreeSeriesItem and add a colorIndex property:

public static class MapTreeSeriesItem extends TreeSeriesItem {
    private Number colorIndex;

    public Number getColorIndex() {
        return colorIndex;
    }

    public void setColorIndex(Number colorIndex) {
        this.colorIndex = colorIndex;
    }
}

You then need to specify a color index for each of the top-level series items:

TreeSeries series = new TreeSeries();

MapTreeSeriesItem apples = new MapTreeSeriesItem();
apples.setId("A");
apples.setName("Apples");
apples.setColorIndex(0);

...

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

...

series.addAll(apples, anneA, rickA, peterA);

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 makes the tree map alternate the drawing direction between vertical and horizontal. The next level’s starting direction is always the opposite of the previous. The default value is false.

layoutAlgorithm

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

layoutStartingDirection

Defines which direction the layout algorithm starts drawing. Possible values are defined in TreeMapLayoutStartingDirection enum: HORIZONTAL and VERTICAL. The 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 is the same as the tree structure. The default 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 earlier example. 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. The 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, the parent is rendered as a root item.

Tree Map example

Open in a
new tab
Chart chart = new Chart(ChartType.TREEMAP);

Configuration conf = chart.getConfiguration();

conf.getTooltip().setEnabled(true);

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

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

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

level1.setDataLabels(dataLabels);
plotOptions.setLevels(level1);

TreeSeries series = createSeries();
series.setPlotOptions(plotOptions);

chart.getConfiguration().addSeries(series);

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

Polygons

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

Polygons consist of connected data points. 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 chart options can be configured in a PlotOptionsPolygon object, although it doesn’t have any chart-type-specific options.

Polygon example

Open in a
new tab
Chart chart = new Chart(ChartType.POLYGON);

Configuration conf = chart.getConfiguration();

chart.setId("chart");
conf.getChart().setZoomType(Dimension.XY);
conf.disableCredits();
conf.setTitle("Height vs Weight");
conf.setSubTitle("Polygon series in Vaadin Charts.");

Tooltip tooltip = conf.getTooltip();
tooltip.setHeaderFormat("<b>{series.name}</b><br>");
tooltip.setPointFormat("{point.x} cm, {point.y} kg");

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 plotOptionsScatter = new PlotOptionsScatter();
DataSeries scatter = new DataSeries();
scatter.setPlotOptions(plotOptionsScatter);
scatter.setName("Observations");
fillScatter(scatter);

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

polygon.add(new DataSeriesItem(153, 42));
polygon.add(new DataSeriesItem(149, 46));
polygon.add(new DataSeriesItem(149, 55));
polygon.add(new DataSeriesItem(152, 60));
polygon.add(new DataSeriesItem(159, 70));
polygon.add(new DataSeriesItem(170, 77));
polygon.add(new DataSeriesItem(180, 70));
polygon.add(new DataSeriesItem(180, 60));
polygon.add(new DataSeriesItem(173, 52));
polygon.add(new DataSeriesItem(166, 45));
conf.addSeries(polygon);

conf.addSeries(scatter);

Flags

Flags is a special chart type for annotating a series or the X axis with call-out labels. Flags denote 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

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. This 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 that 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, Open-High-Low-Close (OHLC), and candlestick series, the flag can be placed on the open, high, low, or close key. Defaults to y.

Data

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

Example

The following annotates 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);

Flags example

Open in a
new tab
Chart chart = new Chart(ChartType.SPLINE);

Configuration configuration = chart.getConfiguration();
configuration.setTitle("Average fruit consumption during one week");

XAxis xAxis = new XAxis();
xAxis.setCategories("Monday", "Tuesday", "Wednesday", "Thursday",
        "Friday", "Saturday", "Sunday");
configuration.addxAxis(xAxis);

YAxis yAxis = new YAxis();
yAxis.setTitle("Fruit units");
configuration.addyAxis(yAxis);

Tooltip tooltip = new Tooltip();
tooltip.setShared(true);
tooltip.setValueSuffix(" units");
configuration.setTooltip(tooltip);

configuration.addSeries(new ListSeries("John", 3, 4, 3, 5, 4, 10, 12));

ListSeries janeSeries = new ListSeries("Jane", 1, 3, 4, 3, 3, 5, 4);
janeSeries.setId("jane");
configuration.addSeries(janeSeries);

DataSeries onSeriesFlags = new DataSeries("On series");
PlotOptionsFlags onSeriesFlagsOptions = new PlotOptionsFlags();
onSeriesFlagsOptions.setOnSeries("jane");
onSeriesFlagsOptions.setShape(FlagShape.SQUAREPIN);
onSeriesFlags.setPlotOptions(onSeriesFlagsOptions);
onSeriesFlags.add(new FlagItem(2, "On series"));
onSeriesFlags.add(new FlagItem(5, "On series"));
configuration.addSeries(onSeriesFlags);

DataSeries onAxisFlags = new DataSeries("On axis");
onAxisFlags.setPlotOptions(new PlotOptionsFlags());
onAxisFlags.add(new FlagItem(3, "On axis"));
configuration.addSeries(onAxisFlags);

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 consists of vertical lines, each having a horizontal tick mark both on the left and the right side. The top and bottom ends of the vertical line show the highest and lowest prices during the time period. The tick mark on the left side of the vertical line shows the opening price, and the tick mark 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();

When using DataProviderSeries, you need to specify the functions used to retrieve 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, OHLC and candlestick charts contain a lot of data, so it’s 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 the value of the groupPixelWidth property in the DataGrouping, the points are grouped into appropriate groups so that each group is around 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() allows you to set the fill and border colors of the candlestick that show a rise in the values. The default colors are white.

OHLC example

Open in a
new tab

Candlestick example

Open in a
new tab
Chart chart = new Chart(ChartType.CANDLESTICK);


Configuration configuration = chart.getConfiguration();
configuration.getTitle().setText("AAPL Stock Price");

DataSeries dataSeries = new DataSeries();

PlotOptionsCandlestick plotOptionsCandlestick = new PlotOptionsCandlestick();
DataGrouping grouping = new DataGrouping();
grouping.addUnit(new TimeUnitMultiples(TimeUnit.WEEK, 1));
grouping.addUnit(new TimeUnitMultiples(TimeUnit.MONTH, 1, 2, 3, 4, 6));
plotOptionsCandlestick.setDataGrouping(grouping);
dataSeries.setPlotOptions(plotOptionsCandlestick);
for (Number[] data : getRawData()) {
    OhlcItem item = new OhlcItem();
    item.setX(data[0]);
    item.setLow(data[1]);
    item.setHigh(data[2]);
    item.setClose(data[3]);
    item.setOpen(data[4]);
    dataSeries.add(item);
}
configuration.setSeries(dataSeries);

RangeSelector rangeSelector = new RangeSelector();
rangeSelector.setSelected(1);
configuration.setRangeSelector(rangeSelector);

chart.setTimeline(true);

Data Labels

You can change how labels that appear next to data points are displayed for some series types (not available for BOXPLOT and ERRORBAR).

The data labels properties in the DataLabels class are summarized in the following:

  • align: HorizontalAlign (left, center, right)

  • allowOverlap: Boolean whether to allow data labels to wrap

  • borderRadius: Number with the border radius in pixels

  • className: String a class name for the data label to be added to the node to allow custom styles by CSS

  • enabled: Boolean whether the data label is enabled or disabled

  • format: String a format string for the label (see more at "Using Format Strings")

  • formatter: String a format string containing a JavaScript function for the label (see more at "Using a JavaScript Formatter")

Also, data labels can be styled by CSS with .highcharts-data-label-box and .highcharts-data-label class names.

Data Point Markers

Line charts and other charts that display data points, such as scatter 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 stroke and a fill color, which are set using a CSS selector .highcharts-markers .highcharts-point.

// Set radius and symbol
marker.setRadius(10);
marker.setSymbol(MarkerSymbolEnum.DIAMOND);

point.setMarker(marker);
series.add(point);

Marker size is determined by the radius parameter, which is given in pixels.

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

Marker Symbols

Markers are visualized either with a shape or an image symbol. You can choose the shape from many 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 the frontend folder, you can determine its URL as follows:

String url = "frontend/img/smiley.png";
marker.setSymbol(new MarkerSymbolUrl(url));

You can use width and height to resize the marker. The radius property isn’t applicable to image symbols.

3D Charts

Most chart types can be made 3-dimensional by adding 3D options to the chart. You can rotate the charts, set up the view distance, and define the thickness of the chart features, among other things. You can also set up a 3D axis frame around a chart.

charts 3d pie
3D Charts

3D Options

3D view has to be enabled in the Options3d configuration, along with other parameters. As a minimum, to have some 3D effect, you need to rotate the chart according to the alpha and beta parameters.

Consider a basic scatter chart as an example. The basic configuration for scatter charts is described elsewhere, but consider how to make it 3D.

Chart chart = new Chart(ChartType.SCATTER);
Configuration conf = chart.getConfiguration();
... other chart configuration ...

// In 3D!
Options3d options3d = new Options3d();
options3d.setEnabled(true);
options3d.setAlpha(10);
options3d.setBeta(30);
options3d.setDepth(135); // Default is 100
options3d.setViewDistance(100); // Default
conf.getChart().setOptions3d(options3d);

The 3D options are as follows:

alpha

The vertical tilt (pitch) in degrees.

beta

The horizontal tilt (yaw) in degrees.

depth

Depth of the third (Z) axis in pixel units.

enabled

Whether 3D plot is enabled. The default is false.

frame

Defines the 3D frame, which consists of a back, bottom, and side panels that display the chart grid.

Frame frame = new Frame();
Back back=new Back();
back.setColor(SolidColor.BEIGE);
back.setSize(1);
frame.setBack(back);
options3d.setFrame(frame);
viewDistance

View distance for creating perspective distortion. The default is 100.

3D Plot Options

The above sets up the general 3D view, but you also need to configure the 3D properties of the actual chart type. The 3D plot options are chart-type-specific. For example, a pie has depth (or thickness), which you can configure as follows:

// Set some plot options
PlotOptionsPie options = new PlotOptionsPie();
... Other plot options for the chart ...

options.setDepth(45); // Our pie is quite thick

conf.setPlotOptions(options);

3D Data

For some chart types, such as pies and columns, the 3D view is merely a visual representation for one- or two-dimensional data. Some chart types, such as scatter charts, also feature a third, depth axis, for data points. Such data points can be given as DataSeriesItem3d objects.

The Z parameter is depth and isn’t scaled; there is no configuration for the depth or Z axis. You need to handle scaling yourself, as in the following.

// Orthogonal data points in 2x2x2 cube
double[][] points = { {0.0, 0.0, 0.0}, // x, y, z
                      {1.0, 0.0, 0.0},
                      {0.0, 1.0, 0.0},
                      {0.0, 0.0, 1.0},
                      {-1.0, 0.0, 0.0},
                      {0.0, -1.0, 0.0},
                      {0.0, 0.0, -1.0}};

DataSeries series = new DataSeries();
for (int i=0; i<points.length; i++) {
    double x = points[i][0];
    double y = points[i][1];
    double z = points[i][2];

    // Scale the depth coordinate, as the depth axis is
    // not scaled automatically
    DataSeriesItem3d item = new DataSeriesItem3d(x, y,
        z * options3d.getDepth().doubleValue());
    series.add(item);
}
conf.addSeries(series);

Previously, we defined 7 orthogonal data points in the 2&mult;2&mult;2 cube centered at the origin. The 3D depth was set to 135 earlier. The result is illustrated in 3D Scatter Chart.

charts 3d scatter
3D Scatter Chart

Distance Fade

To add a bit more 3D effect, you can do some tricks, such as calculate the distance of the data points from a viewpoint and set the marker size and color according to the distance.

public double distanceTo(double[] point, double alpha,
                         double beta, double viewDist) {
    final double theta = alpha * Math.PI / 180;
    final double phi   = beta * Math.PI / 180;
    double x = viewDist * Math.sin(theta) * Math.cos(phi);
    double y = viewDist * Math.sin(theta) * Math.sin(phi);
    double z = - viewDist * Math.cos(theta);
    return Math.sqrt(Math.pow(x - point[0], 2) +
                     Math.pow(y - point[1], 2) +
                     Math.pow(z - point[2], 2));
}

Using the distance requires some assumptions about the scaling and such, but for the data points (as defined earlier) in range -1.0 to +1.0, we could do as follows:

...
DataSeriesItem3d item = new DataSeriesItem3d(x, y,
    z * options3d.getDepth().doubleValue());

double distance = distanceTo(new double[]{x,y,z},
                             alpha, beta, 2);

Marker marker = new Marker(true);
marker.setRadius(1 + 10 / distance);
item.setMarker(marker);

series.add(item);

Here the view distance is in the scale of the data coordinates, while the distance defined in the 3D options has different definition and scaling. With the above settings, which are somewhat exaggerated to illustrate the effect, the result is shown in 3D Distance Fade.

charts 3d distance
3D Distance Fade

7D9B93CE-C74C-4440-869F-9594622310AD