Skip to content

Latest commit

 

History

History
596 lines (518 loc) · 19.4 KB

File metadata and controls

596 lines (518 loc) · 19.4 KB
title Charts
icon #pro/ChartPie

<MetaData lang="en-US" isPro meta={{ preset: [{ client: '@univerjs/preset-sheets-advanced', locale: '@univerjs/preset-sheets-advanced/locales/en-US', style: '@univerjs/preset-sheets-advanced/lib/index.css', }], plugins: [{ client: '@univerjs-pro/sheets-chart', locale: '@univerjs-pro/sheets-chart/locale/en-US', }, { client: '@univerjs-pro/sheets-chart-ui', locale: '@univerjs-pro/sheets-chart-ui/locale/en-US', style: '@univerjs-pro/sheets-chart-ui/lib/index.css', }], server: false, }} />

Charts are an important tool for data visualization, helping users 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' // [!code ++]
import UniverPresetSheetsAdvancedEnUS from '@univerjs/preset-sheets-advanced/locales/en-US' // [!code ++]
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'
import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'
import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing' // [!code ++]
import UniverPresetSheetsDrawingEnUS from '@univerjs/preset-sheets-drawing/locales/en-US' // [!code ++]
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'

import '@univerjs/preset-sheets-core/lib/index.css'
import '@univerjs/preset-sheets-drawing/lib/index.css' // [!code ++]
import '@univerjs/preset-sheets-advanced/lib/index.css' // [!code ++]

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

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

{/* ### Presets and Configuration */}

Plugin Mode

Installation

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

Usage

import { UniverSheetsChartPlugin } from '@univerjs-pro/sheets-chart' // [!code ++]
import { UniverSheetsChartUIPlugin } from '@univerjs-pro/sheets-chart-ui' // [!code ++]
import SheetsChartUIEnUS from '@univerjs-pro/sheets-chart-ui/locale/en-US' // [!code ++]
import SheetsChartEnUS from '@univerjs-pro/sheets-chart/locale/en-US' // [!code ++]
import { LocaleType, mergeLocales, Univer } from '@univerjs/core'

import '@univerjs-pro/sheets-chart/facade' // [!code ++]

import '@univerjs-pro/sheets-chart-ui/lib/index.css' // [!code ++]

const univer = new Univer({
  locale: LocaleType.En_US,
  locales: {
    [LocaleType.En_US]: mergeLocales(
      SheetsChartEnUS, // [!code ++]
      SheetsChartUIEnUS, // [!code ++]
    ),
  },
})

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

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

Supported Chart Types

Univer Sheets supports the following chart types:

Chart Type Description
Column Column chart
ColumnStacked Stacked column chart
ColumnPercentStacked Percent stacked column chart
Bar Bar chart
BarStacked Stacked bar chart
BarPercentStacked Percent stacked bar chart
Line Line chart
Area Area chart
AreaStacked Stacked area chart
AreaPercentStacked Percent stacked area chart
Pie Pie chart
Doughnut Doughnut chart
Radar Radar chart
Scatter Scatter chart
Bubble Bubble chart
Combination Combination chart
WordCloud Word cloud chart
Funnel Funnel chart
Relation Relation chart
Waterfall Waterfall chart
Pareto Pareto chart
Sankey Sankey chart
Heatmap Heatmap chart
Boxplot Boxplot chart

Facade API

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

Importing

Only plugin mode requires manually importing the Facade package. Preset mode already includes the corresponding Facade package, so no extra import is needed.
import '@univerjs-pro/sheets-chart/facade'

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:

Method Description
addRange Specify the data source range for the chart
setPosition Set the chart position using row and column anchors
setAbsolutePosition Set the chart position using pixel values
setChartType Set the chart type
setWidth Set the chart width
setHeight Set the chart height
setOptions Set chart options
setTransposeRowsAndColumns Transpose rows and columns
setTheme Set the theme
setXAxisTitle Set the X-axis title
setYAxisTitle Set the Y-axis title
setRightYAxisTitle Set the right Y-axis title
setXAxisTextStyle Set the X-axis title style
setYAxisTextStyle Set the Y-axis title style
setRightYAxisTextStyle Set the right Y-axis title style
setInvalidValueStrategy Set the display mode for empty cells
setAxisPointerStyle Sets the axis pointer style
setAllSeriesStyle Sets styles for all series
setSeriesStyle Sets the series style by series index
build Generate 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 ```typescript export interface IChartBuildOptions { /** * @property {string} [title] The title of the chart. */ title?: { /** * @property {string} [titlePosition] The position of the chart title. */ position?: TitlePositionEnum /** * @property {string} [titleAlignment] The alignment of the chart title.The possible values are 'left', 'center' & 'right'. */ titleAlignment: LabelAlignEnum } & 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} [yAxisTitle] The 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?: Partial seriesStyleMap?: { [id: string]: ISeriesStyle } /** * @property {string} [area] The area of line/area chart. */ area?: { lineStyle: AreaLineStyle } /** * @property {RadarShape} [radar] The radar of the chart. */ radar?: { /** * @property {RadarShape} [shape] The shape of the radar chart. */ shape?: RadarShape /** * @property {boolean} [fill] True if the radar chart is filled; false otherwise. */ fill?: boolean } /** * @property {string} [pie] The pie configuration of the chart. */ pie?: { /** * @property {number} [doughnutHole] The size of the hole in the center of the pie chart. */ doughnutHole: number /** * @property {string} [borderColor] The color of the border around the pie chart. */ borderColor: string /** * @property {boolean} [hasPaddingAngle] True if the pie chart has a padding angle. */ hasPaddingAngle: boolean /** * @property {boolean} [isHalfPie] True if the pie chart is a half pie chart. */ isHalfPie: boolean /** * @property {boolean} [rosePie] True if the pie chart is a rose pie chart. */ rosePie: boolean /** * @property {boolean} [showLabelLine] True if the pie chart shows label lines. */ showLabelLine: boolean } /** * @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 ```typescript 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 fWorksheet.updateChart(newChartInfo) } }, 3000)

</details>

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:

```typescript
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)
  • LineChartBuilder
Method Description
setLineStyle Set the line style, 'line' - straight line, 'smooth' - smooth line, 'step' - step line
setDataPointShape Set the data point shape, refer to LinePointShape for supported shapes
setDataPointColor Set the data point color
setDataPointSize Set the data point size
build Generate builder info for inserting/updating the chart
  • PieChartBuilder
Method Description
setDoughnutHole Set the size of the doughnut hole, range is 0-1
setBorderColor Set the color of the border around the pie chart
setHasPaddingAngle Set whether the pie chart sectors have padding angles (separation)
setIsHalfPie Set whether it is a half pie chart
setRosePie Set whether it is a rose chart
setShowLabelLine Show label lines
build Generate builder info for inserting/updating the chart
  • RadarChartBuilder
Method Description
setShape Set the default shape of the radar chart, currently supported values are: 'polygon' - polygon, 'circle' - circle
setFill Whether to fill the radar chart
build Generate 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:

Method Description
getRange Get the chart data source range
getSeriesData Get the series data
getCategoryData Get the category data
updateRange Update 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])
  console.log(fWorksheet.getCharts())
}, 3000)

Chart Theme

The FWorksheet.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)