|
|
使用 Plotly.js 的 makeSubplots 创建子图,以下是简单示例:
- // 引入 plotly.js
- // 假设已通过 CDN 引入:<script src="[url=https://cdn.plot.ly/plotly-2.27.0.min.js"></script>]https://cdn.plot.ly/plotly-2.27.0.min.js"></script>[/url]
- // 创建 2x2 子图布局
- Plotly.makeSubplots({
- rows: 2,
- cols: 2,
- subplotTitles: ['折线图', '散点图', '柱状图', '混合图']
- }).then(function(fig) {
- // 添加折线图到子图 (1,1)
- Plotly.addTrace(fig, {
- x: [1, 2, 3],
- y: [2, 5, 3],
- type: 'scatter',
- mode: 'lines',
- name: '折线'
- }, 1, 1);
- // 添加散点图到子图 (1,2)
- Plotly.addTrace(fig, {
- x: [1, 2, 3],
- y: [4, 1, 6],
- type: 'scatter',
- mode: 'markers',
- name: '散点'
- }, 1, 2);
- // 添加柱状图到子图 (2,1)
- Plotly.addTrace(fig, {
- x: ['A', 'B', 'C'],
- y: [3, 1, 5],
- type: 'bar',
- name: '柱状'
- }, 2, 1);
- // 添加混合图到子图 (2,2) - 同时包含折线和柱状
- Plotly.addTrace(fig, {
- x: [1, 2, 3],
- y: [2, 4, 1],
- type: 'bar',
- name: '柱状',
- marker: {color: 'orange'}
- }, 2, 2);
- Plotly.addTrace(fig, {
- x: [1, 2, 3],
- y: [3, 2, 4],
- type: 'scatter',
- mode: 'lines+markers',
- name: '折线'
- }, 2, 2);
- // 绘制图形
- Plotly.newPlot('plotDiv', fig.data, fig.layout);
- });
复制代码
注意事项:
1. 需要先创建 HTML 容器:<div id="plotDiv"></div>
2. makeSubplots 返回 Promise,需用 .then() 处理
3. addTrace 参数:图形对象、行号、列号(从 1 开始计数)
4. 可通过 subplotTitles 设置每个子图标题
其他常用参数:
- vertical_spacing:垂直间距
- horizontal_spacing:水平间距
- shared_xaxes:共享 X 轴
- shared_yaxes:共享 Y 轴
这样就能快速创建多子图布局了!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|