图表组合
创建高级自定义图表。
概述
@mui/x-charts
遵循基于上下文提供器的架构。总体思路是将你的系列和坐标轴定义传递给单个组件:<ChartContainer />
。此组件转换数据并使其可用于其子组件。
基于容器提供的数据,你可以使用提供的子组件(例如 <LinePlot />
或 <ChartsYAxis />
)渲染一些图形元素。或者你可以创建你自己的组件。
容器选项
响应式
有两种类型的图表容器可用:<ChartContainer />
和 <ResponsiveChartContainer />
。顾名思义,它们之间唯一的区别是响应性。
第一个容器需要你提供 width
和 height
属性。相比之下,<ResponsiveChartContainer />
会自动调整其尺寸以适应父元素定义的可用空间。
以下演示允许你在使用 <ChartContainer />
且 width
设置为 500
和 height
设置为 300
的图表,以及使用 <ResponsiveChartContainer />
的图表之间切换,以便你可以看到它们之间的区别。
属性
图表容器获取所有不特定于单个图形元素的属性。这包括
系列
series
属性是系列定义的数组。你可以在它们各自的文档页面中找到关于每种特定系列类型的解释:折线图,柱状图,饼图,和 散点图。
当使用单个图表组件时,库可以猜测你正在定义的系列类型。例如,柱状图组件假定 series
的类型为 'bar'
。
通过组合,图表容器无法猜测系列类型,因此你必须显式定义它。
<BarChart
series={[{
data: [1, 2, 3] // No need to specify it is a bar series
}]}
/>
<ChartContainer
series={[
{ data: [1, 2, 3], type: 'bar' }, // This series is for the bar chart
{ data: [3, 2, 1], type: 'line' } // This series is for the line chart
]}
>
<BarPlot /> {/* Will only display series with type: 'bar' */}
<LinePlot /> {/* Will only display series with type: 'line' */}
</ChartContainer>
这些系列可以使用 dataset
属性,方式与单组件图表相同——有关更多详细信息,请参阅柱状图文档中的使用数据集。
在下一个演示中,图表是通过组合 <BarPlot />
和 <LinePlot />
组件制作的。通过修改系列 type
属性,你可以在渲染折线图和柱状图之间切换。
<ResponsiveChartContainer
series={[
{ type, data: [1, 2, 3, 2, 1] },
{ type, data: [4, 3, 1, 3, 4] },
]}
>
<BarPlot />
<LinePlot />
<ChartsXAxis label="X axis" position="bottom" axisId="x-axis-id" />
</ResponsiveChartContainer>
子组件
绘图
要显示数据,你有名为 <XxxPlot />
的组件,例如 <LinePlot />
、<AreaPlot />
、<MarkPlot />
、<BarPlot />
等。
裁剪
为确保图表元素保持在指定的绘图区域内,请使用 ChartsClipPath
组件。此组件定义一个矩形裁剪路径,该路径充当边界。
- 定义裁剪路径:使用
<ChartsClipPath id={clipPathId} />
为绘图区域建立裁剪路径。clipPathId
必须是唯一标识符。 - 包裹图表:将要裁剪的图表元素包含在
<g>
元素中。将clipPath
属性设置为url(#${clipPathId})
以引用先前定义的裁剪路径。示例:<g clipPath={`url(#${clipPathId})`}>
<ChartContainer>
<g clipPath={`url(#${clipPathId})`}>
// The plotting to clip in the drawing area.
<ScatterPlot />
<LinePlot />
</g>
<ChartsClipPath id={clipPathId} /> // Defines the clip path of the drawing area.
</ChartContainer>
以下演示允许你切换散点图和折线图的裁剪。观察折线标记如何延伸到裁剪区域之外,并在坐标轴之上渲染。
坐标轴
要添加坐标轴,你可以使用 <ChartsXAxis />
和 <ChartsYAxis />
,如坐标轴页面中所定义。
它接受一个 axisId
属性,指示应渲染容器中定义的哪个坐标轴。如果未提供 axisId
,它将选择第一个。
网格
要添加网格,你可以使用 <ChartsGrid />
组件。
有关更多信息,请参阅坐标轴—网格文档。
附加信息
要向图表添加图例,你可以使用 <ChartsLegend />
。
大多数属性在图例页面中进行了解释。演示使用 slotProps.legend
对象,但通过组合,你可以将属性直接传递给 <ChartsLegend />
。
// With single component chart
<BarChart
slotProps={{
legend: {
direction: 'row',
}
}}
/>
// With composition
<ChartContainer>
<ChartsLegend direction="row" />
</ChartContainer>
交互
你还可以添加交互式元素,例如 <ChartsAxisHighlight />
和 <ChartsTooltip />
。
API
请参阅下面的文档,以获取此处提及的组件的所有可用属性和类的完整参考。