ChartsSpreadsheet
Column, bar, line, area, pie, doughnut, scatter, bubble, radar and combo charts with trendlines, error bars, data labels and axis options, that float over the sheet, update live from cell ranges and round-trip to xlsx.
Charts float over the grid like pictures. Each series points at cell ranges, so a chart redraws as soon as a value it uses changes. Charts are drawn as SVG inside the page, with no canvas and no extra dependency.
const id = sheet.addChart({
type: 'column',
title: 'Q3 spend by department',
series: [
{ name: "='Q3 Budget'!B1", categories: "'Q3 Budget'!A2:A4", values: "'Q3 Budget'!B2:B4" },
{ name: "='Q3 Budget'!C1", categories: "'Q3 Budget'!A2:A4", values: "'Q3 Budget'!C2:C4" },
],
legend: 'bottom',
anchor: { cell: 'G2', width: 480, height: 280 },
});Chart types#
type |
Notes |
|---|---|
column, bar |
Clustered by default. stacked: true stacks the series and stacked: 'percent' stacks them to 100%. |
line |
smooth: true draws curves. Empty cells leave a gap. |
area |
Overlapping by default; stacked works as for columns. |
pie, doughnut |
Use the first series. Each category gets its own colour and legend entry. |
scatter |
categories holds the x values and values the y values. |
bubble |
As scatter, plus sizes for each bubble's area. |
radar |
One polygon per series around the categories. |
combo |
Columns, lines and areas together. Set type on each series; without it the first series is a column and the rest are lines. secondaryAxis: true plots a series against a second value axis on the right. |
waterfall |
The first series. Each value is a step from the running total; the points listed in series[0].subtotals (zero-based) are totals drawn from zero. Rises, falls and totals have their own colours. |
histogram |
The values of the first series, counted in bins. bins: { width } or bins: { count } sets them; without it the width is 3.49 × standard deviation ÷ ∛n, the rule Excel uses. The first bin includes its lower edge, every bin its upper edge. |
treemap, sunburst |
One tile or segment per positive value. A categories range of two or more columns groups by its first column and labels by its last. |
funnel |
One centred bar per category, widths in proportion to the values. |
boxWhisker |
One box per series, or per category and series when the categories repeat: exclusive quartiles, the median, a cross at the mean, whiskers to the furthest point within 1.5 interquartile ranges, and a dot for each outlier. |
stock |
Three series (high, low, close) draw a range with a closing tick; four (open, high, low, close) draw candlesticks, green when the close is at or above the open. |
The last seven kinds have no trendlines, error bars, data labels, axis options or stacking, and the Format chart pane sets their title and fills only. Waterfall and histogram are in the Insert > Chart menu; the others are added with addChart() or come from a file.
Series#
A series' values, categories and sizes are references, written as in a formula without the leading =: B2:B13, 'Q3 Budget'!B2:B4 or a defined name. Unqualified references are read from the sheet the chart sits on. name is literal text such as 'Forecast', or a reference such as ='Q3 Budget'!B1. color overrides the default palette, which follows the Office theme colours.
Other options:
titleandaxisTitles: { x, y }add text.legendis'right','bottom','top','left','topRight'or'none'. Charts with several series, and pie and doughnut charts, show a legend on the right by default.'topRight'puts it at the top of the right side.dataLabels: truewrites each value next to its bar or point, and a percentage on pie slices. See Data labels.
Trendlines#
A series can carry any number of trendlines. Each is fitted to the series by least squares and drawn as a dashed line.
sheet.addChart({
type: 'scatter',
series: [
{
name: 'Signups by visits',
categories: 'B2:B40',
values: 'C2:C40',
trendlines: [
{ type: 'linear', forward: 500, displayEquation: true, displayRSquared: true },
{ type: 'movingAverage', period: 4, name: 'Four-week average', color: '#7030a0' },
],
},
],
anchor: { cell: 'H2', width: 480, height: 300 },
});type |
Fit |
|---|---|
linear |
y = mx + b |
polynomial |
A polynomial of order 2 to 6. The default is 2; other values are brought into that range. |
exponential |
y = a·e^(bx). Points with y of zero or less are left out. |
logarithmic |
y = a·ln(x) + b. Points with x of zero or less are left out. |
power |
y = a·x^b. Points with x or y of zero or less are left out. |
movingAverage |
The mean of the last period values, starting at the first full window. The default period is 2. |
forward and backward extend a fitted line past the last and before the first point, in units of the x axis; on a chart with categories one unit is one category, and the line stops at the edge of the plot. displayEquation and displayRSquared write the equation and R² at the end of the line. R² of exponential and power fits is measured on the logarithms, as Excel does. name replaces the default tooltip text, such as "Linear (Orders)", and color the series colour.
For a chart with categories, x is 1 for the first category, 2 for the second and so on. Trendlines are drawn on column, bar, line, area, scatter and bubble charts and on those series of a combo chart. Stacked charts, pie, doughnut and radar charts have none, and a trendline does not get its own legend entry.
Error bars#
series: [
{
values: 'B2:B13',
categories: 'A2:A13',
errorBars: [{ type: 'percentage', value: 10, show: 'plus', color: '#475467' }],
},
];type |
Length of each bar |
|---|---|
fixed |
value, 1 by default. |
percentage |
value percent of the point, 5 by default. |
standardDeviation |
value times the standard deviation of the series, 1 by default. As in Excel, these bars are centred on the mean of the series, not on each point. |
standardError |
The standard error of the series. |
custom |
The amounts in the ranges plus and minus, one cell per point. These ranges follow inserted rows and renamed sheets like the series ranges. |
show is 'both' (the default), 'plus' or 'minus'. endCap: false leaves out the short line at each end. direction: 'x' draws horizontal bars on scatter and bubble charts, which can have one set of bars in each direction; other charts have one set along the value axis. The value axis grows to fit the bars. Error bars are drawn on the same chart types as trendlines and not on stacked series.
Data labels#
dataLabels: true on the chart labels every series. dataLabelOptions sets how; a series can carry its own dataLabels with the same options, or dataLabels: false to go without.
sheet.addChart({
type: 'column',
dataLabels: true,
dataLabelOptions: { placement: 'insideEnd', numberFormat: '#,##0' },
series: [
{ name: 'Plan', values: 'B2:B5', categories: 'A2:A5' },
{ name: 'Actual', values: 'C2:C5', categories: 'A2:A5', dataLabels: { showSeriesName: true, showValue: true } },
{ name: 'Forecast', values: 'D2:D5', categories: 'A2:A5', dataLabels: false },
],
anchor: { cell: 'G2', width: 480, height: 280 },
});| Option | Meaning |
|---|---|
placement |
Column and bar charts: 'outsideEnd' (the default), 'insideEnd', 'center', 'insideBase'. Line, scatter and bubble charts: 'above' (the default), 'below', 'left', 'right', 'center'. Pie and doughnut charts: inside the slice by default, 'center', or 'outsideEnd'. 'bestFit' is the default of the chart type. |
showValue, showCategoryName, showSeriesName, showPercentage |
What the label says, joined by commas. With none of them set, a label shows the value, and the percentage on a pie. Once one is set, only those set to true are shown. The percentage is the point's share of its series. |
numberFormat |
An Excel number format code for the value. |
Axes and gridlines#
axes holds options for up to four axes: x and y, and secondaryX and secondaryY for the series of a combo chart plotted with secondaryAxis: true. x is the category axis, or the horizontal value axis of a scatter or bubble chart; y is the value axis. On a bar chart the category axis runs down the side and the value axis along the bottom.
sheet.updateChart(id, {
axes: {
x: { reversed: true, majorGridlines: true },
y: { min: 0, max: 60000, majorUnit: 15000, numberFormat: '#,##0', minorGridlines: true },
},
});| Option | Meaning |
|---|---|
min, max |
Limits of a value axis. Values outside are drawn at the edge. Ignored when the minimum is not below the maximum. |
majorUnit |
Distance between tick labels and major gridlines of a value axis. |
logBase |
Makes a value axis logarithmic with this base, from 2 to 1000. Values of zero or less are drawn at the bottom of the axis. |
reversed |
Turns the axis round: the highest value at the bottom, or the last category first. |
numberFormat |
Number format code of the tick labels. On a category axis it applies to categories that are numbers or dates. |
labelPosition |
'nextTo' (the default) and 'low' keep the labels at the usual side, 'high' moves them to the opposite side of the plot, 'none' hides them. |
hidden |
Hides the axis: no labels, and for the category axis no axis line. The secondary category axis is hidden unless you set hidden: false, which repeats the category labels along the top. |
majorGridlines |
On by default for y, off for the others. |
minorGridlines |
Off by default. Four lines between two major ones, or one per multiple on a logarithmic axis. |
Options that do not fit an axis are ignored: a category axis has no limits, unit or logarithmic scale. Pie and doughnut charts have no axes, and a radar chart is drawn without axis options.
Other chart kinds#
A file can hold charts of kinds that are not modelled: surface charts, pie-of-pie charts and map charts. They are not drawn and are not in getCharts(). A Pareto chart is drawn as its histogram, without the cumulative line. Their parts, with the styles and colours they refer to, are written back byte for byte when you export, and the import report lists them under Charts of other kinds with the kind of each. They stay in the file when you edit cells or other charts; deleting their sheet removes them.
Charts from a selection#
Insert > Chart offers the ten chart types and builds the chart from the selected cells, or from the block of data around the active cell. The series are worked out the way Excel does it:
- Leading columns that hold text are categories, not series. The first of them labels the axis; further text columns are ignored. A column of text between number columns is skipped as well.
- Each column with numbers is a series. Its name comes from the header row when the selection includes one, or from the row directly above the selection when that row holds text.
- A first column of dates is used as categories. A first column of numbers, such as years, is used as categories when the corner cell above it is empty.
- When the data has more columns than rows, the series run along the rows and the header row labels the axis.
- A scatter chart uses the first number column for x and one series for each further column; a bubble chart takes columns in pairs of y and size; a combo chart draws the last series as a line.
So selecting Department | Owner | Plan rows gives one series named "Plan" with the departments on the axis, not an empty series for the owners.
The new chart is placed beside the selection where there is room in the visible part of the sheet, otherwise below it or to its left. It never covers the selected data or other filled cells: if every place next to the selection holds data, it goes to the first free columns to the right. It is selected, so the arrow keys and Delete act on it straight away. Each item of the chart menu carries an icon id (chartColumn, chartBar, chartLine, chartArea, chartPie, chartDoughnut, chartScatter, chartBubble, chartRadar, chartCombo) and shows the icon once the icon set has one under that id; until then the items are text only.
Position and size#
anchor places the top-left corner at a cell plus an optional pixel offset (offsetX, offsetY), with a width and height in pixels. The chart moves with its cell when rows or columns are inserted or deleted, and stays put when you scroll the frozen panes.
Click a chart to select it. Drag it to move it, or drag the square in its corner to resize it. With a chart selected, the arrow keys move it by one pixel (ten with Shift), Delete removes it and Escape returns the focus to the grid. Every change is undoable. Charts cannot be moved on read-only spreadsheets or on protected sheets unless the protection allows editObjects.
Changing charts in code#
| Method | Purpose |
|---|---|
addChart(chart, sheet?) |
Adds a chart and returns its id. An id you pass is kept if it is unique. |
updateChart(id, changes) |
Changes any property except the id. |
removeChart(id) |
Deletes the chart. |
getCharts(sheet?) |
Returns copies of a sheet's charts. |
Chart references follow sheet renames and row and column insertions, like formulas do.
Format chart pane#
Double-click a chart, press Alt+Enter on a selected chart, choose Insert > Format chart or call openDialog('formatChart') to open the pane beside the grid. Escape closes it. Each change is one undo step.
| Section | What it sets | Model property |
|---|---|---|
| Chart title | Text, font, size in points, bold, italic, text colour | title, titleStyle |
| Horizontal and vertical axis title | The same six settings for each primary axis | axisTitles, axisTitleStyles |
| Series | Colour of the chosen series; marker shape and size on line, scatter and radar series | series[n].color, series[n].marker |
| Fills | Chart area and plot area colour, or automatic | fill, plotFill |
sheet.updateChart(id, {
titleStyle: { family: 'Georgia', size: 16, italic: true, color: '#0550ae' },
axisTitles: { x: 'Month', y: 'Units' },
axisTitleStyles: { y: { bold: true } },
fill: '#fff8e1',
plotFill: undefined,
});A property passed as undefined to updateChart is cleared. Marker shapes are none, circle, square, diamond, triangle and x. A chart with an explicit fill picks dark or light text for its labels from the fill, so it stays readable in both themes.
In a chart that came from an xlsx file these edits are written into the original chart part: a new title text keeps the title's fonts, gradient and effects, a new title size changes only the size, a series colour replaces only that series' fill and keeps its outline. See what an edit keeps.
Accessibility#
A chart is exposed as an image named by its title and type, for example "Q3 spend by department, column chart". Each bar, slice and point carries a tooltip with its series, category and value. Put the numbers a reader needs in the cells as well; a chart is a picture of them, not a replacement.
Excel files#
Charts are saved to and read from xlsx as native Excel charts. See Excel files for details.