グラフを作成して編集する
セル範囲からシートにグラフを追加し、調整して、何がプロットされるかを読み戻すときの手順です。全オプションは グラフ に、呼び出しは WASM API と Python API にあります。
範囲からグラフを作成する
ws.addChart は Excel の「グラフの挿入」と同じ規則で範囲からグラフを作ります。先頭の行と列が文字列なら系列名と項目になり、残りの列がそれぞれ系列になります。anchor はグラフの枠をセル単位(0 始まりの行と列)で配置します。戻り値の Chart ハンドルは、ws.chart(id) や ws.listCharts() が返すものと同じオブジェクトです。
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 は、barDirection で Bar を指定しない限り縦棒になります。addChart で作成できる種類は Bar、Line、Area、Pie、Doughnut、Scatter です。
プロットを変更する
グラフは 0 から番号が付いたプロットグループを 1 つ以上持ちます。setType(plot, type) はグループの種類を置き換え、各系列の参照はそのまま残します。updatePlot(plot, patch) は棒の間隔と重なり、円グラフの最初のスライスの角度、ドーナツの穴の大きさ、要素ごとに色を変えるかどうかを設定します。
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 2種類を変えたときに参照以外の何が残るか(系列の色やデータラベルなど)は、Excel で同じ変更をしたときの規則に従います。詳しくは グラフ を参照してください。
軸を編集する
updateAxis(axis, patch) は 1 本の軸を変更します。軸は { kind: ChartAxisKind.Value } のように種類で指定するか、getProperties().axes に並ぶ id で指定します。パッチでは最小値と最大値、主目盛と補助目盛の間隔、タイトル、目盛線、表示形式、交差位置、対数目盛を設定できます。省いたキーは現在の値を保ち、最小値・最大値や主目盛・補助目盛の間隔に null を渡すと自動に戻ります。Python では 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 #,##0系列を編集・追加する
系列はプロットグループと seriesId(getProperties() に並ぶ c:idx)で指定します。updateSeries は系列の参照、塗りつぶし、線、マーカー、データラベルを変更します。addSeries は系列を追加してその id を返します。参照は数式の文字列で渡し、values は必須です。
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 }) は新しい範囲からすべての系列を一度に作り直し、removeSeries(plot, seriesId) は系列を 1 つ削除します。
プロットするデータを読む
getProperties() はグラフの定義(参照、書式、軸、凡例)を返します。getData() は系列を現在のセル値で解決するので、元のセルを編集すればグラフ側の呼び出しなしで結果に反映されます。各系列の values は Float64Array(Python ではリスト)で、categories.labels に項目の文字列が入ります。
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) は、範囲、系列の方向、見出しの扱いを変えた場合の系列を、グラフを変更せずに解決します。グラフのダイアログで、適用前にプレビューするときに使えます。
ワークブックを保存する
save() はグラフをシートの描画パーツに書き出し、Excel が再計算前に表示するキャッシュ値も一緒に保存します。読み込んだワークブックでは、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) # Sales凡例、タイトル、データ要素の書式、グラフフィルター、空白セルのプロット方法は グラフ で説明しています。