Create and edit a chart
Use this page to add a chart to a sheet from a range of cells, adjust it, and read back what it plots. Charts lists every option, and the calls are in the WASM API and the Python API.
Create a chart from a range
ws.addChart builds a chart from a range the way Excel's Insert Chart does: the first row and column become series names and categories when they hold text, and each remaining column becomes a series. anchor places the chart frame by cell (0-based rows and columns). The returned Chart handle is the same object ws.chart(id) and ws.listCharts() return.
import createFormulon, { ChartPlotType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Quarter', 'North', 'South'],
['Q1', 120, 80],
['Q2', 150, 95],
['Q3', 170, 110],
])
const chart = ws.addChart({
type: ChartPlotType.Bar,
range: 'A1:C4',
title: 'Sales',
anchor: { fromRow: 5, fromCol: 0, toRow: 20, toCol: 6 },
})
const series = chart.getProperties().plots[0].series
console.log(series.length) // 2
console.log(series[0].name.formula) // Sheet1!$B$1
console.log(series[0].values.formula) // Sheet1!$B$2:$B$4
console.log(ws.listCharts()[0] === chart) // true
} finally {
wb.dispose()
}from formulon import ChartInput, ChartPlotType, DrawingAnchorInput, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Quarter", "North", "South"],
["Q1", 120, 80],
["Q2", 150, 95],
["Q3", 170, 110],
])
chart = ws.add_chart(ChartInput(
type=ChartPlotType.BAR,
range="A1:C4",
title="Sales",
anchor=DrawingAnchorInput(from_row=5, from_col=0, to_row=20, to_col=6),
))
series = chart.get_properties().plots[0].series
print(len(series)) # 2
print(series[0].name.formula) # Sheet1!$B$1
print(series[0].values.formula) # Sheet1!$B$2:$B$4
print(ws.list_charts()[0] is chart) # TrueChartPlotType.Bar draws vertical columns unless barDirection says Bar. The types addChart creates are Bar, Line, Area, Pie, Doughnut and Scatter.
Change the plot
A chart holds one or more plot groups, numbered from 0. setType(plot, type) replaces a group's type and keeps each series' references. updatePlot(plot, patch) sets the gap width and overlap of bars, the angle of the first pie slice, the doughnut hole size and whether each point gets its own colour.
import createFormulon, { ChartGrouping, ChartPlotType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [['Quarter', 'North', 'South'], ['Q1', 120, 80], ['Q2', 150, 95], ['Q3', 170, 110]])
const chart = ws.addChart({ type: ChartPlotType.Bar, range: 'A1:C4' })
chart.updatePlot(0, { gapWidthPct: 50, overlapPct: 100 })
let plot = chart.getProperties().plots[0]
console.log(plot.gapWidthPct, plot.overlapPct) // 50 100
chart.setType(0, ChartPlotType.Bar, { grouping: ChartGrouping.Stacked })
plot = chart.getProperties().plots[0]
console.log(plot.grouping === ChartGrouping.Stacked) // true
chart.setType(0, ChartPlotType.Line)
plot = chart.getProperties().plots[0]
console.log(plot.type === ChartPlotType.Line, plot.series.length) // true 2
} finally {
wb.dispose()
}from formulon import ChartGrouping, ChartInput, ChartPlotType, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [["Quarter", "North", "South"], ["Q1", 120, 80], ["Q2", 150, 95], ["Q3", 170, 110]])
chart = ws.add_chart(ChartInput(type=ChartPlotType.BAR, range="A1:C4"))
chart.update_plot(0, gap_width_pct=50, overlap_pct=100)
plot = chart.get_properties().plots[0]
print(plot.gap_width_pct, plot.overlap_pct) # 50 100
chart.set_type(0, ChartPlotType.BAR, grouping=ChartGrouping.STACKED)
plot = chart.get_properties().plots[0]
print(plot.grouping == ChartGrouping.STACKED) # True
chart.set_type(0, ChartPlotType.LINE)
plot = chart.get_properties().plots[0]
print(plot.type == ChartPlotType.LINE, len(plot.series)) # True 2What a type change keeps besides the references, such as series colours and data labels, follows Excel's rules for the same change; Charts describes them.
Edit an axis
updateAxis(axis, patch) changes one axis. Address the axis by kind with { kind: ChartAxisKind.Value }, or by the id that getProperties().axes lists. The patch sets the bounds, the major and minor units, the title, gridlines, the number format, the crossing point and a logarithmic scale; a key left out keeps its value, and null returns a bound or unit to automatic. Python also takes a bare ChartAxisKind.
import createFormulon, { ChartAxisKind, ChartPlotType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [['Quarter', 'North', 'South'], ['Q1', 120, 80], ['Q2', 150, 95], ['Q3', 170, 110]])
const chart = ws.addChart({ type: ChartPlotType.Bar, range: 'A1:C4' })
chart.updateAxis({ kind: ChartAxisKind.Value }, {
min: 0,
max: 200,
majorUnit: 50,
title: 'Units',
numberFormat: '#,##0',
majorGridlines: true,
})
const axis = chart.getProperties().axes.find((a) => a.kind === ChartAxisKind.Value)
console.log(axis.min, axis.max, axis.majorUnit) // 0 200 50
console.log(axis.title.text, axis.numberFormat) // Units #,##0
} finally {
wb.dispose()
}from formulon import ChartAxisKind, ChartInput, ChartPlotType, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [["Quarter", "North", "South"], ["Q1", 120, 80], ["Q2", 150, 95], ["Q3", 170, 110]])
chart = ws.add_chart(ChartInput(type=ChartPlotType.BAR, range="A1:C4"))
chart.update_axis(
ChartAxisKind.VALUE,
min=0,
max=200,
major_unit=50,
title="Units",
number_format="#,##0",
major_gridlines=True,
)
axis = next(a for a in chart.get_properties().axes if a.kind == ChartAxisKind.VALUE)
print(axis.min, axis.max, axis.major_unit) # 0.0 200.0 50.0
print(axis.title.text, axis.number_format) # Units #,##0Edit and add series
A series is addressed by its plot group and its seriesId, the c:idx that getProperties() lists. updateSeries changes the series' references, fill, line, markers and data labels. addSeries appends a series and returns its id; its references are formula text, and values is required.
import createFormulon, { ChartPlotType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Quarter', 'North', 'South', 'West'],
['Q1', 120, 80, 60],
['Q2', 150, 95, 70],
['Q3', 170, 110, 80],
])
const chart = ws.addChart({ type: ChartPlotType.Bar, range: 'A1:C4' })
chart.updateSeries(0, 0, { fill: { color: '#2F6FED' }, labels: { showValue: true } })
const id = chart.addSeries(0, {
name: 'Sheet1!$D$1',
categories: 'Sheet1!$A$2:$A$4',
values: 'Sheet1!$D$2:$D$4',
})
const series = chart.getProperties().plots[0].series
console.log(id, series.length) // 2 3
console.log((series[0].fill.color.base.argb & 0xffffff).toString(16)) // 2f6fed
console.log(series[0].labels.showValue) // true
} finally {
wb.dispose()
}from formulon import ChartInput, ChartPlotType, ChartSeriesInput, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Quarter", "North", "South", "West"],
["Q1", 120, 80, 60],
["Q2", 150, 95, 70],
["Q3", 170, 110, 80],
])
chart = ws.add_chart(ChartInput(type=ChartPlotType.BAR, range="A1:C4"))
chart.update_series(0, 0, fill={"color": "#2F6FED"}, labels={"show_value": True})
series_id = chart.add_series(0, ChartSeriesInput(
name="Sheet1!$D$1",
categories="Sheet1!$A$2:$A$4",
values="Sheet1!$D$2:$D$4",
))
series = chart.get_properties().plots[0].series
print(series_id, len(series)) # 2 3
print(format(series[0].fill.color.base.argb & 0xFFFFFF, "x")) # 2f6fed
print(series[0].labels.show_value) # TruesetSource({ range }) rebuilds every series from a new range in one call, and removeSeries(plot, seriesId) drops one.
Read the plotted data
getProperties() returns the chart definition: references, formatting, axes and legend. getData() resolves the series against the current cell values, so it reflects edits to the source cells without any chart call. Each series carries its values as a Float64Array (a list in Python), and categories.labels holds the category text.
import createFormulon, { ChartPlotType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [['Quarter', 'North', 'South'], ['Q1', 120, 80], ['Q2', 150, 95], ['Q3', 170, 110]])
const chart = ws.addChart({ type: ChartPlotType.Bar, range: 'A1:C4', title: 'Sales' })
ws.setValue('B2', 125)
const data = chart.getData()
console.log(data.titleText) // Sales
console.log(data.categories.labels.join()) // Q1,Q2,Q3
const [north, south] = data.series
console.log(north.name, Array.from(north.values).join()) // North 125,150,170
console.log(south.name, Array.from(south.values).join()) // South 80,95,110
} finally {
wb.dispose()
}from formulon import ChartInput, ChartPlotType, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [["Quarter", "North", "South"], ["Q1", 120, 80], ["Q2", 150, 95], ["Q3", 170, 110]])
chart = ws.add_chart(ChartInput(type=ChartPlotType.BAR, range="A1:C4", title="Sales"))
ws["B2"] = 125
data = chart.get_data()
print(data.title_text) # Sales
print(",".join(data.categories.labels)) # Q1,Q2,Q3
north, south = data.series
print(north.name, north.values) # North [125.0, 150.0, 170.0]
print(south.name, south.values) # South [80.0, 95.0, 110.0]getPreview(overrides) resolves the series as if a different range, direction or header choice were applied, without changing the chart, which suits a chart dialog that previews before applying.
Save the workbook
save() writes the chart into the drawing part of its sheet, with the cached values Excel shows before it recalculates. A loaded workbook lists the chart again through ws.listCharts().
import createFormulon, { ChartPlotType } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
let bytes
try {
const ws = wb.sheet(0)
ws.setValues('A1', [['Quarter', 'North', 'South'], ['Q1', 120, 80], ['Q2', 150, 95], ['Q3', 170, 110]])
ws.addChart({ type: ChartPlotType.Line, range: 'A1:C4', title: 'Sales' })
bytes = wb.save()
} finally {
wb.dispose()
}
const back = formulon.Workbook.load(bytes)
try {
const [chart] = back.sheet(0).listCharts()
console.log(chart.getProperties().plots[0].type === ChartPlotType.Line) // true
console.log(chart.getData().titleText) // Sales
} finally {
back.dispose()
}from formulon import ChartInput, ChartPlotType, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [["Quarter", "North", "South"], ["Q1", 120, 80], ["Q2", 150, 95], ["Q3", 170, 110]])
ws.add_chart(ChartInput(type=ChartPlotType.LINE, range="A1:C4", title="Sales"))
wb.save("chart.xlsx")
with Workbook.load("chart.xlsx") as back:
chart = back[0].list_charts()[0]
print(chart.get_properties().plots[0].type == ChartPlotType.LINE) # True
print(chart.get_data().title_text) # SalesLegends, the title, point formatting, the chart filter and how blanks plot are covered in Charts.