Charts

GitHubEdit on GitHub
Preset Info
@univerjs/preset-sheets-advanced
Server Required
No

Charts are an important tool for data visualization, helping users to understand and analyze data more intuitively. In Univer Sheets, the chart feature provides various types of charts, including bar charts, line charts, pie charts, etc. Users can choose the appropriate chart type to display data according to their needs.

Preset Mode

The chart feature is included in the @univerjs/preset-sheets-advanced preset.

Installation

The UniverSheetsAdvancedPreset preset from @univerjs/preset-sheets-advanced depends on the UniverSheetsDrawingPreset preset at runtime. Please install @univerjs/preset-sheets-drawing first.

npm install @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced

Usage

import { UniverSheetsAdvancedPreset } from '@univerjs/preset-sheets-advanced'
import UniverPresetSheetsAdvancedEnUS from '@univerjs/preset-sheets-advanced/locales/en-US'
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'
import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'
import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing'
import UniverPresetSheetsDrawingEnUS from '@univerjs/preset-sheets-drawing/locales/en-US'
import { createUniver, LocaleType, merge } from '@univerjs/presets'

import '@univerjs/preset-sheets-core/lib/index.css'
import '@univerjs/preset-sheets-drawing/lib/index.css'
import '@univerjs/preset-sheets-advanced/lib/index.css'

const { univerAPI } = createUniver({
  locale: LocaleType.En_US,
  locales: {
    [LocaleType.En_US]: merge(
      {},
      UniverPresetSheetsCoreEnUS,
      UniverPresetSheetsDrawingEnUS, 
      UniverPresetSheetsAdvancedEnUS, 
    ),
  },
  presets: [
    UniverSheetsCorePreset(),
    UniverSheetsDrawingPreset(), 
    UniverSheetsAdvancedPreset(), 
  ],
})

If you have a commercial license for Univer, please refer to Using License in Client for configuration.

Plugin Mode

Installation

npm install @univerjs-pro/sheets-chart @univerjs-pro/sheets-chart-ui

Usage

import { UniverSheetsChartPlugin } from '@univerjs-pro/sheets-chart'
import { UniverSheetsChartUIPlugin } from '@univerjs-pro/sheets-chart-ui'
import SheetsChartUIEnUS from '@univerjs-pro/sheets-chart-ui/locale/en-US'
import SheetsChartEnUS from '@univerjs-pro/sheets-chart/locale/en-US'
import { LocaleType, merge, Univer } from '@univerjs/core'

import '@univerjs-pro/sheets-chart-ui/facade'

import '@univerjs-pro/sheets-chart-ui/lib/index.css'

const univer = new Univer({
  locale: LocaleType.En_US,
  locales: {
    [LocaleType.En_US]: merge(
      {},
      SheetsChartEnUS, 
      SheetsChartUIEnUS, 
    ),
  },
})

univer.registerPlugin(UniverSheetsChartPlugin)
univer.registerPlugin(UniverSheetsChartUIPlugin)

If you have a commercial license for Univer, please refer to Using License in Client for configuration.

Enums

Show Enums
export enum ChartAttributeBits {
  Stack = 1 << 30,
  PercentStack = 1 << 29 | ChartAttributeBits.Stack,
  Horizontal = 1 << 28,
}

export enum ChartTypeBits {
  None = 0,
  Line = 1 << 1,
  Column = 1 << 2,
  ColumnStacked = ChartTypeBits.Column | ChartAttributeBits.Stack,
  ColumnPercentStacked = ChartTypeBits.Column | ChartAttributeBits.PercentStack,
  Bar = 1 << 2 | ChartAttributeBits.Horizontal,
  BarStacked = ChartTypeBits.Bar | ChartAttributeBits.Stack,
  BarPercentStacked = ChartTypeBits.Bar | ChartAttributeBits.PercentStack,
  Pie = 1 << 3,
  Doughnut = 1 << 8 | ChartTypeBits.Pie,
  Area = 1 << 4,
  AreaStacked = ChartTypeBits.Area | ChartAttributeBits.Stack,
  AreaPercentStacked = ChartTypeBits.Area | ChartAttributeBits.PercentStack,
  Radar = 1 << 5,
  Scatter = 1 << 6,
  Combination = 1 << 7,
}

Facade API

Complete Facade API type definitions can be found in the FacadeAPI.。

You can use the Facade API in Univer Sheets to create, configure, and manage charts. The Facade API is a programming interface for charts that can help you use chart features more conveniently.

Insert Chart

FWorksheet.newChart() method is used to create a chart builder, returning an instance of FChartBuilderBase. You can chain method calls to set various properties of the chart.

Then call build() to generate an IChartBuilderInfo object, and use the FWorksheet.insertChart(chartBuildInfo: IChartBuilderInfo) method to insert the chart into the worksheet.

const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

// Create a column chart with data source A1:D6.
// The starting position is upper-left corner of cell B2.
// The width of the chart is 600 and the height is 400.
const chartInfo = fWorksheet.newChart()
  .setChartType(univerAPI.Enum.ChartType.Column)
  .addRange('A1:D6')
  .setPosition(1, 1, 0, 0)
  .setWidth(600)
  .setHeight(400)
  .build()
await fWorksheet.insertChart(chartInfo)

Here are some member methods on FChartBuilderBase:

MethodDescription
addRangeSpecify the data source range for the chart
setPositionSet the chart position using row and column anchors
setAbsolutePositionSet the chart position using pixel values
setChartTypeSet the chart type
setWidthSet the chart width
setHeightSet the chart height
setOptionsSet chart options
setTransposeRowsAndColumnsTranspose rows and columns
setThemeSet the theme
setXAxisTitleSet the X-axis title
setYAxisTitleSet the Y-axis title
setRightYAxisTitleSet the right Y-axis title
setXAxisTextStyleSet the X-axis title style
setYAxisTextStyleSet the Y-axis title style
setRightYAxisTextStyleSet the right Y-axis title style
setInvalidValueStrategySet the display mode for empty cells
setAxisPointerStyleSets the axis pointer style
setALLSeriesStyleSets styles for all series
setSeriesStyleSets the series style by series index
buildGenerate builder info for inserting/updating the chart

Univer supports various chart configurations, which can be set using the setOptions method. The configuration options are defined in the IChartBuildOptions interface.

Show Configuration
export interface IChartBuildOptions {
  /**
   * @property {string} [title] The title of the chart.
   */
  title?: {
    /**
     * @property {string} [titlePosition] The position of the chart title.
     */
    position?: TitlePositionEnum
  } & IChartTextStyle
  /**
   * @property {string} [legend] The legend of the chart.
   */
  legend?: {
    /**
     * @property {string} [legendPosition] The position of the legend.The possible values are 'top', 'bottom', 'left', 'right' & 'hide'.
     */
    position?: LegendPositionEnum
    /**
     * @property {number} [fontSize] The font size of the legend.
     */
    fontSize?: number
    /**
     * @property {string} [color] The font color of the legend.
     */
    color?: string
    /**
     * @property {string} [bold] The font style of the legend.
     */
    bold?: boolean
    /**
     * @property {string} [italic] The font weight of the legend.
     */
    italic?: boolean
    /**
     * @property {SelectModeEnum} [selectMode] The select mode of the legend.The possible values are 'single', 'multiple' & 'close'.
     */
    selectMode?: SelectModeEnum
  }
  /**
   * @property {string} [xAxisTitle] The x-axis title of the chart.
   * @example
   * ```typescript
   * chartBuilder.setOptions('xAxisTitle.content', 'xAxis Title text')
   * .setOptions('xAxisTitle.font', 1)
   * .setOptions('xAxisTitle.fontSize', 12)
   * .setOptions('xAxisTitle.fontColor', '#ff0000')
   * .build();
   * ```
   */
  xAxisTitle?: IChartTextStyle
  /**
   * @property {string} [rightYAxisTitle] The right y-axis title of the chart.
   */
  yAxisTitle?: IChartTextStyle
  /**
   * @property {string} [rightYAxisTitle] The right y-axis title of the chart.
   */
  rightYAxisTitle?: IChartTextStyle
  xAxis?: IAxisOptions
  yAxis?: IAxisOptions
  yRightAxis?: IAxisOptions
  axisPointer?: {
    /**
     * @property {string} [indicatorLineType] The line type of the axis pointer.
     */
    indicatorLineType?: string
    /**
     * @property {ChartBorderDashType} [indicatorLineColor] The line color of the axis pointer.The maybe values are 'solid', 'dotted', 'dashed'.
     */
    indicatorLineColor?: ChartBorderDashType
    /**
     * @property {string} [indicatorLabelColor] The line width of the axis pointer.
     */
    indicatorLabelColor?: string
    /**
     * @property {string} [indicatorLabelTextColor] The font color of the axis pointer.
     */
    indicatorLabelTextColor?: string
  }
  allSeriesStyle?: IAllSeriesStyle
  seriesStyleMap?: {
    [id: string]: ISeriesStyle
  }
  /**
   * @property {string} [area] The area of line/area chart.
   */
  area?: {
    lineStyle: AreaLineStyle
  }
  /**
   * @property {string} [backgroundColor] The background color of the chart.
   */
  backgroundColor?: string
  /**
   * @property {string} [borderColor] The border color of the chart.
   */
  borderColor?: string
  /**
   * @property {boolean} [gradientFill] Whether to use gradient fill.This property does not work in line charts.
   */
  gradientFill?: boolean
  /**
   * @property {string} [theme] The theme of the chart.
   */
  theme?: string
  /**
   * @property {InvalidValueType} [invalidValueType] The display mode for empty cells.
   */
  invalidValueType?: InvalidValueType
}

Configuration options are set through the setOptions method, there are the following two methods:

  • setOptions(optionPath, optionVal): setOptions('legend.color', '#ff0000')
  • setOptions('', IChartBuildOptions): setOptions('', { legend: { color: '#ff0000', bold: true } })
Example: Create a Line Chart
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

// Create a line chart
const chartInfo = fWorksheet.newChart()
  // As a line chart
  .asLineChart()
  // Set the data source A1:D6
  .addRange('A1:D6')
  // Set the starting position to the upper-left corner of cell B2
  .setPosition(1, 1, 0, 0)
  // Set the indicator line style
  .setAxisPointerStyle({
    indicatorLabelColor: '#ff0000',
    indicatorLineType: univerAPI.Enum.ChartBorderDashType.Solid,
    indicatorLineColor: '#00ff00',
    indicatorLabelTextColor: '#0000ff',
  })
  // Set the data point size to 10
  .setDataPointSize(10)
  // Set the data point shape to circular
  .setDataPointShape(univerAPI.Enum.LinePointShape.CIRCLE)
  // Generate builder info
  .build()
const fChart = await fWorksheet.insertChart(chartInfo)

// Update the chart after 3 seconds
setTimeout(() => {
  if (fChart) {
    // Get the first series data
    const first = fChart.getSeriesData()[0]
    // Set the color of the first series to red
    const newChartInfo = fWorksheet.newChart(fChart)
      .setSeriesStyle(first.index, {
        color: '#ff0000',
      })
      .build()
    // Update the chart
    fSheet.updateChart(newChartInfo)
  }
}, 3000)

Univer provides the following builders to create specific types of charts, which can be created using fWorkSheet.newChart().asLineChart() and so on. They derive from FChartBuilderBase and have some unique configurations:

const lineChartBuilder = fWorkSheet.newChart().asLineChart()
const pieChartBuilder = fWorkSheet.newChart().asPieChart()
const radarChartBuilder = fWorkSheet.newChart().asRadarChart()

// Or you can use the following method to create a chart builder
const chartBuilder = fWorkSheet.newChart()
  .setChartType(univerAPI.Enum.ChartType.Column)
MethodDescription
setLineStyleSet the line style, 'line' - straight line, 'smooth' - smooth line, 'step' - step line
setDataPointShapeSet the data point shape, refer to LinePointShape for supported shapes
setDataPointColorSet the data point color
setDataPointSizeSet the data point size
buildGenerate builder info for inserting/updating the chart
MethodDescription
setDoughnutHoleSet the size of the doughnut hole, range is 0-1
setBorderColorSet the color value of the pie chart sectors
setHasPaddingAngleSet whether the pie chart sectors have padding angles (separation)
setIsHalfPieSet whether it is a half pie chart
setRosePieSet whether it is a rose chart
setShowLabelLineShow label lines
buildGenerate builder info for inserting/updating the chart
MethodDescription
setShapeSet the default shape of the radar chart, currently supported values are: 'polygon' - polygon, 'circle' - circle
setFillWhether to fill the radar chart
buildGenerate builder info for inserting/updating the chart

Get Charts

FWorksheet.getCharts() method is used to get all charts in the current worksheet, returning an array of FChart objects.

const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

// Get all charts on the active sheet.
const charts = fWorksheet.getCharts()

Here are some member methods on FChart:

MethodDescription
getRangeGet the chart data source range
getSeriesDataGet the series data
getCategoryDataGet the category data
updateRangeUpdate the chart data source range

Update Chart

The FWorksheet.updateChart(chartBuildInfo: IChartBuilderInfo) method is used to update the chart, passing in an IChartBuilderInfo object to update the chart configuration.

const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

// Create a column chart with data source A1:D6.
// The starting position is upper-left corner of cell B2.
const chartInfo = fWorksheet.newChart()
  .setChartType(univerAPI.Enum.ChartType.Column)
  .addRange('A1:D6')
  .setPosition(1, 1, 0, 0)
  .build()
await fWorksheet.insertChart(chartInfo)

// Get all charts on the active sheet.
const charts = fWorksheet.getCharts()

// Update the first chart after 3 seconds.
setTimeout(() => {
  const newChartInfo = fWorksheet.newChart(charts[0])
    .asLineChart()
    .setOptions('legend.position', univerAPI.Enum.LegendPositionEnum.Right)
    .build()
  fWorksheet.updateChart(newChartInfo)
}, 3000)

Remove Chart

The FWorksheet.removeChart(chart: FChart) method is used to remove a chart, passing in an FChart object to remove the specified chart.

const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

// Create a column chart with data source A1:D6.
// The starting position is upper-left corner of cell B2.
const chartInfo = fWorksheet.newChart()
  .setChartType(univerAPI.Enum.ChartType.Column)
  .addRange('A1:D6')
  .setPosition(1, 1, 0, 0)
  .build()
await fWorksheet.insertChart(chartInfo)

// Get all charts on the active sheet.
const charts = fWorksheet.getCharts()

// Remove the first chart after 3 seconds.
setTimeout(async () => {
  await fWorksheet.removeChart(charts[0])
  fWorksheet.getCharts()
}, 3000)

Chart Theme

The FChartBuilderBase.registerChartTheme(themeName: string, theme: IEchartTheme) method is used to register a chart theme, passing in a theme name and theme object to register a custom theme.

Univer chart is implemented based on the echarts library, so you can use the echart theme builder tool to create your custom theme. You can create your own theme on this website and download it as a configuration file. Use the following API to use your custom theme:

const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

// register your theme
const theme = { // your theme object
  version: 1,
  themeName: 'myTheme',
  theme: {
    // ... Some code is omitted for brevity
    color: [
      '#893448',
      '#d95850',
      '#eb8146',
      '#ffb248',
      '#f2d643',
      '#ebdba4',
    ],
    // ... Some code is omitted for brevity
    visualMapColor: [
      '#893448',
      '#d95850',
      '#eb8146',
      '#ffb248',
      '#f2d643',
      'rgb(247,238,173)',
    ],
    // ... Some code is omitted for brevity
    axes: [],
    // ... Some code is omitted for brevity
  },
}
fWorksheet.registerChartTheme('myTheme', theme)

// use your theme for chart
const chartInfo = fWorksheet.newChart()
  .asLineChart()
  .addRange('A1:D6')
  .setPosition(1, 1, 0, 0)
  .setTheme('myTheme')
  .build()
await fWorksheet.insertChart(chartInfo)