superset集成echarts--添加Line折线图
环境
Python 3.8.10
windows 10 专业版
node v16.16.0
superset1.5
一、\superset\superset-frontend\src\visualizations
1、在\superset\superset-frontend\src\visualizations下新增几个对应的文件
images -----> 存放新增图表的预览图
LineExamples.js ------> 新图表渲染逻辑
LineExamplesChartPlugin.js ---------> superset中渲染构造新图表
RectLineExamples.js ---------------> 注册新图表
transformProps.js ---------------> 前后端数据传递
注:需要创建什么组件,就要新增一个对应的文件夹,名为xxx,文件夹下有xxx.js、xxxChartPlugin.js、Rectxxx.js、transformProps.js,images下有thumbnail.png
2、 images下新增预览图
thumbnail.js、thumbnailLager.js
图片下载:Examples - Apache ECharts
找到对应的图片,右键图片另存为
3、LineExamples.js
import * as echarts from 'echarts';
import * as d3 from 'd3';
import PropTypes from 'prop-types';
import { CategoricalColorNamespace } from '@superset-ui/core';// 数据类型检查
const propTypes = {data: PropTypes.object,width: PropTypes.number,height: PropTypes.number,
};function LineExamples(element, props) {const { width, height, formData, x_data, series, legend } = props; // transformProps.js 返回的数据const fd = formData;// 配置y轴显示信息const y_min = fd.yMin;const y_max = fd.yMax;// y轴别名const y_axis_label = fd.yAxisLabel;// y轴配置格式const yAxis = {type: 'value',name: 'Y_Axis',axisLabel: {formatter: '{value}',},};if (y_min !== undefined) {yAxis.mix = y_min;}if (y_max != undefined) {yAxis.max = y_max;}if (y_axis_label != undefined) {yAxis.name = y_axis_label;}const div = d3.select(element);const sliceId = `line-${fd.sliceId}`;const html = `<div id=${sliceId} style="height:${height}px; width:${width}px;"></div>`;div.html(html);// init echarts,light 为制定主题,可以查看官方apiconst myChart = echarts.init(document.getElementById(sliceId), 'light');// echarts 渲染图表的数据格式 在官网可以查看const option = {xAxis: {type: 'category',data: x_data},legend: {data: legend, // [] x轴的数据},yAxis: yAxis,series,};myChart.setOption(option);
}LineExamples.displayName = 'Line';
LineExamples.propTypes = propTypes;export default LineExamples;
4.LineExamplesChartPlugin.js
import { t, ChartMetadata, ChartPlugin } from '@superset-ui/core';
import transformProps from './transformProps';
import thumbnail from './images/thumbnail.png';const metadata = new ChartMetadata({name: t('Line'),description: '',credits: ['https://www.echartsjs.com/examples/en/editor.html?c=mix-line-bar'],thumbnail,useLegacyApi: true,
});export default class LineExamplesChartPlugin extends ChartPlugin {constructor() {super({metadata,transformProps,loadChart: () => import('./RectLineExamples.js'), // 前端渲染逻辑});}
}
5、RectLineExamples.js
import {reactify} from '@superset-ui/core';
import Component from './LineExamples';export default reactify(Component);
6、transformProps.js
export default function transformProps(chartProps) {const { width, height, queriesData, formData } = chartProps;// formData 前端页面的数据 queriesData 后端返回的数据return {data: queriesData[0].data,width,height,formData,legend: queriesData[0].data.legend,x_data: queriesData[0].data.x_data,series: queriesData[0].data.data,};}
二、注册插件流程
1、superset\superset-frontend\src\visualizations\presets\MainPreset.js文件
注册插件
import LineExamplesChartPlugin from '../Line/LineExamplesChartPlugin';
new LineExamplesChartPlugin().configure({ key: 'line_examples' }),
2、\superset\superset-frontend\src\explore\components\controls\VizTypeControl\VizTypeGallery.tsx
//找到DEFAULT_ORDER,末尾添加
'line_examples'
3、superset\superset-frontend\src\explore\controlPanels\LineExamples.js
左侧面板配置文件
/*** https://echarts.apache.org/examples/zh/editor.html?c=mix-line-bar* mix line bar*/import { t, validateNonEmpty } from '@superset-ui/core';const metrics = {type: 'MetricsControl',multi: true,label: t('Metrics'),validators: [validateNonEmpty],mapStateToProps: state => {const { datasource } = state;return {columns: datasource ? datasource.columns : [],savedMetrics: datasource ? datasource.metrics : [],datasource,};},description: t('One or many metrics to display'),};export default {requiresTime: true,controlPanelSections: [{label: t('Chart Options'),expanded: true,controlSetRows: [['color_scheme', 'label_colors'],],},{label: t('X Axis'),expanded: true,controlSetRows: [['groupby'],],},{label: t('Line Type'),expanded: true,controlSetRows: [[{name: 'line_metrics',config: {...metrics, // 继承multi: true, // 多选clearable: true, // 是否可调用, true当作sqlvalidators: [], // 是否可以为空label: t('Line Type Metrics'),description: t('Metrics for which line type are to be displayed'),}}],],},{label: t('Y Axis Scale Value Setting'),expanded: true,controlSetRows: [[{name: 'y_min',config: {type: 'TextControl', //文本输入label: t('Y Min'),renderTrigger: true,isInt: true,description: t('Y Min'),},}, {name: 'y_max',config: {type: 'TextControl',label: t('Y Max'),renderTrigger: true,isInt: true,description: t('Y Max'),}}],[{name: 'y_axis_label',config: {type: 'TextControl',label: t('Y Axis Label'),renderTrigger: true,default: '',},}]],},{label: t('Query'),expanded: true,controlSetRows: [['adhoc_filters', ['row_limit'], ['limit']],],},],// controlOverrides: { },};
5、superset\superset-frontend\src\setup\setupPlugins.ts
import LineExamples from '../explore/controlPanels/LineExamples';
.registerValue('line_examples', LineExamples)
三、后端注册插件部分,并添加数据查询返回方法
1、superset\superset\viz.py
// 找到 METRIC_KEYS 变量 数组末尾添加1个字符串(自定义的组件)
"line_metrics"
2、superset\superset\viz.py 里 def get_subclasses 之前添加
class LineExamplesViz(NVD3Viz):""" line"""viz_type = "line_examples"verbose_name = _("Line")# 是否排序sort_series = False# 是否对time 做处理 _timestampis_timeseries = Falsedef query_obj(self):# check bar column, line column 是否重复# bar_metrics = self.form_data.get('bar_metrics')line_metrics = self.form_data.get('line_metrics')# if not bar_metrics and not line_metrics:# if not line_metrics:# raise Exception(_("Please choose metrics on line or bar type"))# bar_metrics = [] if not bar_metrics else bar_metricsline_metrics = [] if not line_metrics else line_metricsd = super().query_obj()return ddef to_series(self, df, classed=""):"""拼接 前端渲染需要的数据:param df::param classed::return: {'legend':[], 'bar':[], 'line':[]}"""cols = []for col in df.columns:if col == "":cols.append("N/A")elif col is None:cols.append("NULL")else:cols.append(col)df.columns = colsseries = df.to_dict("series")line_metrics = self.form_data.get('line_metrics', [])line_metrics = [] if not line_metrics else line_metricsmetrics = self.all_metricslegend, data = [], []for mt in metrics:m_label = utils.get_metric_name(mt)ys = series[m_label]if df[m_label].dtype.kind not in "biufc":continuelegend.append(m_label)info = {"name": m_label,"data": [ys.get(ds, None) for ds in df.index],"type": ''}if mt in line_metrics:info['type'] = 'line'else:continuedata.append(info)chart_data = {'legend': legend,'data': data,'x_data': [str(ds) if not isinstance(ds, tuple) else ','.join(map(str, ds)) for ds in df.index]}return chart_datadef get_data(self, df: pd.DataFrame):# 后端返回的数据df = df.pivot_table(index=self.groupby, values=self.metric_labels)chart_data = self.to_series(df)return chart_data
四、下载前端依赖
进入superset-fontend
npm install echarts
npm install d3
五、前后端编译完成即可
参考:superset二次开发-添加echarts图表:mix-line-bar_CoCo拓海的博客-CSDN博客_superset增加图表
Superset二次开发--添加新图例_MK_chan的博客-CSDN博客
superset集成echarts--添加Line折线图相关推荐
- echarts type:line 折线图 折线折点样式
echarts type:line 折线图 折线折点样式 series: [{name: '课时',type: 'line',data: [23,60,20,36,23,85],label:{ //折 ...
- superset集成echarts
文章目录 服务地址 前言 集成echarts 集成echarts柱状折线图 mix-line-bar 流程 1. superset-frontend/src/visualizations/ 目录下 2 ...
- echarts柱状图 饼图 折线图
最近大屏项目里做的 首先看看效果 这几个图 我将其标为七个部分 下方成为echarts1,echarts2往后类推 有需要 可以直接拷贝下方代码 推荐一个朋友最近发我的echarts图形地址 ...
- [VUE2/VUE3]基于echarts的动态折线图组件
[VUE2/VUE3]基于echarts的动态折线图组件 时间格式化代码 export default function formatSecond(value: number) {let millis ...
- Echarts动态数据折线图
1.添加引用: <script src="~/Scripts/jquery-3.3.1.js"></script><script src=" ...
- Apache Superset集成Echarts
一.环境准备 1.1 软件环境 npm,nodejs 二.主要步骤 2.1.添加漏斗图模型 cd venv/lib/python2.7/site-packages/supersetvi viz.py ...
- superset集成echarts,自定义图表开发
环境 系统:centos7 python版本:3.7.6 superset版本:0.30 echarts版本:4.2.0以上 说明 因为一开始使用pip(安装方法)直接安装的时候,进入安装路径下没有s ...
- 直播app源代码,echarts 柱状图,折线图互转实例
直播app源代码,echarts 柱状图,折线图互转实例的相关代码 function initDayChart(){var myChart = echarts.init(document.getEle ...
- 在 Echarts 中设置折线图x轴文字的倾斜度
在 Echarts 中设置折线图x轴文字的倾斜度 在工作需求中,有需要把 Echarts 折线图的文字变成倾斜的样式.类似这样的: 这个功能咋实现? 很简单.加一句话就行了 // 配置项 option ...
最新文章
- Tesseract 3 语言数据的训练方法
- linux内网机器访问外网代理设置squid
- hssfcolor 不建议使用_POI导出Excel经典实现
- 关于STM32与SD卡通信的一些思考与总结
- python好学吗mooc中文网-Python语言程序设计
- Spring中的注解@Service @Component @Controller @Repository区别
- js中直接对字符串转义-用于solr ulr 关键词转义
- 大萧条来临前的几大征兆
- python 百度搜索结果_Python洗涤百度搜索结果
- 不用js实现鼠标放上去改变文字内容
- 自动控制理论(1)——自动控制理论概述
- RFID工作原理(图)及标签分类(按供电方式)
- html table最小宽度,table宽度比tbody多1
- 抖快齐聚短剧战场,是加重“同质化”还是搅动“视频格局”?
- java 句柄无效_java.io.IOException: 句柄无效 异常是什么引起的
- ZY Player 2.3.5 中文版 (全网视频播放器)
- 西弗勒斯·斯内普 ---混血王子
- 2019年信息安全工程师上午真题及答案解析
- 安装配置Apache服务器
- 解决方法:点击火车头开心版出现Exception Processing Message 0xc0000005 Parameters