powerMarkers2DCharts.vue 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. <!--
  2. * @Author: your name
  3. * @Date: 2024-09-11 14:32:12
  4. * @LastEditTime: 2025-07-15 16:45:59
  5. * @LastEditors: bogon
  6. * @Description: In User Settings Edit
  7. * @FilePath: /performance-test/src/views/performance/components/chartsCom/powerMarkers2DCharts.vue
  8. -->
  9. <!-- <h1>逐月有功功率散点2D分析</h1>
  10. <h1>偏航控制策略异常检测 2D</h1> 目前没找到这个分析模型-->
  11. <template>
  12. <div style="min-height: 700px">
  13. <!-- 2D散点图 -->
  14. <template>
  15. <div style="display: flex; align-items: center; margin-top: 20px">
  16. <div style="margin-right: 20px; display: flex; align-items: center">
  17. <el-select
  18. size="small"
  19. v-model="color1"
  20. @change="updateChartColor"
  21. placeholder="选择配色方案"
  22. style="width: 200px"
  23. >
  24. <el-option
  25. v-for="(scheme, index) in colorSchemes"
  26. :key="index"
  27. :label="scheme.label"
  28. :value="scheme.colors"
  29. >
  30. <span
  31. v-for="color in scheme.colors.slice(0, 8)"
  32. :style="{
  33. background: color,
  34. width: '20px',
  35. height: '20px',
  36. display: 'inline-block',
  37. }"
  38. ></span>
  39. </el-option>
  40. </el-select>
  41. </div>
  42. <!-- 点大小控制 -->
  43. <div style="display: flex; align-items: center">
  44. <!-- <span style="margin-right: 10px">点大小</span> -->
  45. <el-slider
  46. v-model="pointSize"
  47. :min="1"
  48. :max="15"
  49. :step="1"
  50. label="点的大小"
  51. show-stops
  52. style="width: 150px"
  53. @change="updateChartColor"
  54. ></el-slider>
  55. </div>
  56. </div>
  57. <div
  58. v-loading="loading"
  59. :ref="`plotlyChart-${index}`"
  60. style="height: 600px"
  61. >
  62. <el-empty v-if="isError" description="请求失败"></el-empty>
  63. </div>
  64. </template>
  65. </div>
  66. </template>
  67. <script>
  68. import Plotly from "plotly.js-dist";
  69. import axios from "axios";
  70. import { myMixin } from "@/mixins/chartRequestMixin";
  71. import { colorSchemes } from "@/views/overview/js/colors";
  72. import { mapState } from "vuex";
  73. export default {
  74. mixins: [myMixin],
  75. props: {
  76. fileAddr: {
  77. default: "",
  78. type: String,
  79. },
  80. index: {
  81. type: String,
  82. },
  83. setUpImgData: {
  84. default: () => [],
  85. type: Array,
  86. },
  87. },
  88. data() {
  89. return {
  90. pointSize: 5, // 默认点大小
  91. chartData: {},
  92. chartType: "scatter", // 默认显示散点图
  93. color1: colorSchemes[0].colors, // 默认颜色
  94. selectedPoints: [],
  95. originalColors: [],
  96. originalSizes: [],
  97. // 配色方案列表(每个方案是一个颜色数组)
  98. colorSchemes: [...colorSchemes],
  99. };
  100. },
  101. computed: {
  102. ...mapState("themes", {
  103. themeColor: "themeColor",
  104. }),
  105. },
  106. watch: {
  107. themeColor: {
  108. handler(newval) {
  109. if (newval.length === 0) {
  110. this.color1 = this.colorSchemes[0].colors;
  111. } else {
  112. this.color1 = newval;
  113. }
  114. this.updateChartColor();
  115. },
  116. deep: true,
  117. },
  118. setUpImgData: {
  119. handler(newType) {
  120. this.drawChart();
  121. },
  122. deep: true,
  123. },
  124. },
  125. async mounted() {
  126. this.$nextTick(() => {
  127. this.getData();
  128. // if (this.themeColor.length === 0) {
  129. this.color1 = this.colorSchemes[0].colors;
  130. // } else {
  131. // this.color1 = this.themeColor;
  132. // }
  133. });
  134. },
  135. methods: {
  136. // 根据配色方案设置每个选项的样式
  137. getOptionStyle(scheme) {
  138. return {
  139. background: `linear-gradient(to right, ${scheme
  140. .slice(0, 8)
  141. .join(", ")})`,
  142. color: "#fff",
  143. height: "30px",
  144. lineHeight: "30px",
  145. borderRadius: "0px",
  146. };
  147. },
  148. async getData() {
  149. if (this.fileAddr !== "") {
  150. try {
  151. this.loading = true;
  152. this.cancelToken = axios.CancelToken.source();
  153. const resultChartsData = await axios.get(this.fileAddr, {
  154. cancelToken: this.cancelToken.token,
  155. });
  156. this.chartData = resultChartsData.data;
  157. this.drawChart();
  158. this.isError = false;
  159. this.loading = false;
  160. } catch (error) {
  161. this.isError = true;
  162. this.loading = false;
  163. }
  164. }
  165. },
  166. drawChart() {
  167. // 提取散点数据和线数据
  168. const data =
  169. this.chartData.data &&
  170. this.chartData.data.filter(
  171. (item) => item.enginName !== "合同功率曲线"
  172. )[0]; // 点数据
  173. const lineData =
  174. this.chartData.data &&
  175. this.chartData.data.filter(
  176. (item) => item.enginName === "合同功率曲线"
  177. )[0]; // 线数据
  178. // 提取唯一时间标签,并计算 tickvals 和 ticktext
  179. const uniqueTimeLabels = data.colorbar
  180. ? [...new Set(data.colorbar)]
  181. : [...new Set(data.color)]; // 从 colorbar 中提取唯一的时间标签
  182. // console.log(data.colorbar, "data.colorbar 1");
  183. const tickvals = uniqueTimeLabels.map((label, index) => index + 1); // 根据时间标签生成 tickvals
  184. const ticktext = uniqueTimeLabels.map((dateStr) => {
  185. const date = new Date(dateStr);
  186. return date.toLocaleDateString("en-CA", {
  187. year: "numeric",
  188. month: "2-digit",
  189. }); // 格式化为 'yyyy-MM'
  190. }); // 使用格式化后的时间作为 ticktext
  191. const timeMapping = uniqueTimeLabels.reduce((acc, curr, index) => {
  192. acc[curr] = index + 1;
  193. return acc;
  194. }, {});
  195. // 获取 yData 的最小值和最大值来做比例值的计算
  196. const minValue = Math.min(...tickvals);
  197. const maxValue = Math.max(...tickvals);
  198. // 仅取 this.color1 的前 4 种颜色进行渐变
  199. const colorStops = [
  200. this.color1[0],
  201. this.color1[4],
  202. this.color1[8],
  203. this.color1[12],
  204. ];
  205. // 计算渐变比例
  206. const colors = colorStops.map((color, index) => {
  207. const proportion = index / (colorStops.length - 1); // 计算比例值 (0, 1/3, 2/3, 1)
  208. return [proportion, color]; // 生成颜色映射
  209. });
  210. // 确保至少有 2 个颜色,否则使用默认颜色
  211. if (colors.length < 2) {
  212. colors.push([1, colorStops[colorStops.length - 1] || "#1B2973"]);
  213. }
  214. // 计算颜色值映射
  215. let colorValues = [];
  216. if (data.colorbar) {
  217. colorValues = data.colorbar.map((date) => timeMapping[date]);
  218. } else {
  219. colorValues = data.color.map((date) => timeMapping[date]);
  220. }
  221. let scatterTrace = {}; // 用于存放散点图的 trace
  222. let lineTrace = {}; // 用于存放折线图的 trace
  223. // 保存原始颜色和大小
  224. // this.originalColors = [...data.yData];
  225. this.originalColors = [...colorValues];
  226. this.originalSizes = new Array(data.xData.length).fill(6); // 初始点大小
  227. // 绘制散点图
  228. if (this.chartType === "scatter") {
  229. scatterTrace = {
  230. x: data.xData,
  231. y: data.yData,
  232. mode: "markers", // 散点
  233. type: "scattergl", // 使用散点图
  234. text: data.engineName, // 提示文本
  235. marker: {
  236. color: colorValues, // 使用时间数据来映射颜色
  237. colorscale: this.color1
  238. ? [...colors]
  239. : [
  240. [0, "#F9FDD2"],
  241. [0.15, "#E9F6BD"],
  242. [0.3, "#C2E3B9"],
  243. [0.45, "#8AC8BE"],
  244. [0.6, "#5CA8BF"],
  245. [0.75, "#407DB3"],
  246. [0.9, "#2E4C9A"],
  247. [1, "#1B2973"],
  248. ], // 默认颜色渐变
  249. colorbar: {
  250. title: data.colorbartitle || "月份", // 色标标题
  251. tickvals: tickvals, // 设置刻度值
  252. ticktext: ticktext, // 设置刻度文本
  253. tickmode: "array", // 使用数组模式
  254. // tickangle: -45, // 可选:调整刻度文本的角度
  255. },
  256. size: new Array(data.xData.length).fill(this.pointSize), // 点的大小
  257. },
  258. hovertemplate:
  259. `${this.chartData.xaixs}:` +
  260. ` %{x} <br> ` +
  261. `${this.chartData.yaixs}:` +
  262. "%{y} <br>" +
  263. `时间: %{customdata}<extra></extra>`, // 在 hover 中显示格式化后的时间
  264. customdata: data.colorbar || data.color, // 将格式化后的时间存入 customdata
  265. timedata: data.timeData,
  266. };
  267. }
  268. if (lineData) {
  269. // 绘制折线图
  270. lineTrace = {
  271. x: lineData.xData, // 线数据的 xData
  272. y: lineData.yData, // 线数据的 yData
  273. mode: "lines+markers", // 线和点同时显示
  274. type: "scattergl", // 使用 scattergl 类型
  275. text: lineData.engineName, // 提示文本
  276. line: {
  277. color: "red", // 线条颜色
  278. },
  279. };
  280. }
  281. // 图表布局
  282. const layout = {
  283. title: {
  284. text: data.title,
  285. font: {
  286. size: 16, // 设置标题字体大小(默认 16)
  287. weight: "bold",
  288. },
  289. },
  290. xaxis: {
  291. title: this.chartData.xaixs,
  292. gridcolor: "rgb(255,255,255)", // 网格线颜色
  293. tickcolor: "rgb(255,255,255)",
  294. backgroundcolor: "#e5ecf6",
  295. showbackground: true, // 显示背景
  296. range:
  297. this.chartData.xaixs === "发电机转速(r/min)" ||
  298. this.chartData.xaixs === "发电机转速(r/min)"
  299. ? [1000, 2000]
  300. : undefined,
  301. },
  302. yaxis: {
  303. title: this.chartData.yaixs,
  304. gridcolor: "rgb(255,255,255)", // 网格线颜色
  305. tickcolor: "rgb(255,255,255)",
  306. backgroundcolor: "#e5ecf6",
  307. showbackground: true, // 显示背景
  308. range: this.chartData.yaixs === "桨距角(°)" ? [-1, 20] : undefined,
  309. },
  310. showlegend: false,
  311. plot_bgcolor: "#e5ecf6",
  312. gridcolor: "#fff", // 设置网格线颜色
  313. };
  314. const getChartSetUp = (axisTitle) => {
  315. return this.setUpImgData.find((item) => item.text.includes(axisTitle));
  316. };
  317. const xChartSetUp = getChartSetUp(layout.xaxis.title);
  318. if (xChartSetUp) {
  319. layout.xaxis.dtick = xChartSetUp.dtick;
  320. layout.xaxis.range = [xChartSetUp.min, xChartSetUp.max];
  321. }
  322. const yChartSetUp = getChartSetUp(layout.yaxis.title);
  323. if (yChartSetUp) {
  324. layout.yaxis.dtick = yChartSetUp.dtick;
  325. layout.yaxis.range = [yChartSetUp.min, yChartSetUp.max];
  326. }
  327. // 配置工具栏按钮
  328. const config = {
  329. modeBarButtonsToAdd: [
  330. {
  331. name: "选择",
  332. icon: Plotly.Icons.pencil,
  333. click: (gd) => this.handleSelectClick(gd),
  334. },
  335. {
  336. name: "清除选中",
  337. icon: Plotly.Icons.undo,
  338. click: (gd) => this.handleClearSelect(gd),
  339. },
  340. {
  341. name: "下载CSV文件",
  342. icon: Plotly.Icons.disk,
  343. click: (gd) => this.handleDownloadCSV(gd),
  344. },
  345. ],
  346. modeBarButtonsToRemove: [
  347. "lasso2d", // 移除不需要的工具按钮
  348. // 移除不需要的工具按钮
  349. "lasso2d",
  350. "sendDataToCloud",
  351. "resetCameraLastSave3d",
  352. "resetCameraDefault3d",
  353. "resetCameraLastSave",
  354. "sendDataToCloud",
  355. "zoom2d", // 缩放按钮
  356. "zoom3d",
  357. "plotlylogo2D",
  358. "plotlylogo3D",
  359. ],
  360. displaylogo: false,
  361. editable: true,
  362. scrollZoom: false,
  363. };
  364. // 合并散点和折线图的数据
  365. const traces = [];
  366. if (scatterTrace) traces.push(scatterTrace); // 如果有散点数据
  367. if (lineTrace) traces.push(lineTrace); // 如果有线图数据
  368. this.$nextTick(() => {
  369. // 使用 Plotly 绘制图表
  370. Plotly.react(
  371. this.$refs[`plotlyChart-${this.index}`], // 这里是对 DOM 元素的引用
  372. traces,
  373. layout,
  374. config
  375. ).then(() => {
  376. // 确保图表加载完成后设置工具栏按钮
  377. const plotElement = this.$refs[`plotlyChart-${this.index}`];
  378. Plotly.relayout(plotElement, layout).then(function (gd) {
  379. // 获取工具栏按钮
  380. const toolbar = gd.querySelector(".modebar");
  381. const buttons = toolbar.querySelectorAll(".modebar-btn");
  382. // 定义一个映射对象,方便修改按钮提示
  383. const titleMap = {
  384. "Download plot as a png": "保存图片",
  385. Autoscale: "缩放",
  386. Pan: "平移",
  387. "Zoom out": "缩小",
  388. "Zoom in": "放大",
  389. "Box Select": "选择框操作",
  390. "Lasso Select": "套索选择操作",
  391. "Reset axes": "重置操作",
  392. "Reset camera to default": "重置相机视角",
  393. "Turntable rotation": "转台式旋转",
  394. "Orbital rotation": "轨道式旋转",
  395. };
  396. // 遍历所有按钮,修改它们的 title
  397. buttons.forEach(function (button) {
  398. const dataTitle = button.getAttribute("data-title");
  399. // 如果标题匹配,修改属性值
  400. if (titleMap[dataTitle]) {
  401. button.setAttribute("data-title", titleMap[dataTitle]);
  402. }
  403. });
  404. }); // 使用 relayout 来确保自定义按钮应用
  405. });
  406. });
  407. },
  408. handleSelectClick(gd) {
  409. // 绑定 plotly_click 事件
  410. gd.on("plotly_click", (data) => {
  411. const pointIndex = data.points[0].pointIndex;
  412. const xClick = data.points[0].x;
  413. const yClick = data.points[0].y;
  414. // 将点击的点添加到选中的点数组
  415. this.selectedPoints.push({
  416. x: xClick, // 点击点的 x 坐标
  417. y: yClick, // 点击点的 y 坐标
  418. index: pointIndex, // 点击点的索引
  419. time: data.points[0]?.data?.timedata[data.points[0].pointIndex], // 点击点的时间信息
  420. });
  421. // 初始化颜色和大小数组
  422. let newColors = [...this.originalColors];
  423. let newSize = [...this.originalSizes];
  424. // 如果选中的点数大于等于3,进行多边形选择区域的处理
  425. if (this.selectedPoints.length >= 3) {
  426. const xv = this.selectedPoints.map((p) => p.x);
  427. const yv = this.selectedPoints.map((p) => p.y);
  428. // 判断点是否在多边形内
  429. function inPolygon(x, y, xv, yv) {
  430. let inside = false;
  431. for (let i = 0, j = xv.length - 1; i < xv.length; j = i++) {
  432. const intersect =
  433. yv[i] > y !== yv[j] > y &&
  434. x < ((xv[j] - xv[i]) * (y - yv[i])) / (yv[j] - yv[i]) + xv[i];
  435. if (intersect) inside = !inside;
  436. }
  437. return inside;
  438. }
  439. // 用于跟踪已添加的 (x, y) 组合
  440. const addedPoints = {};
  441. // 遍历图表数据中的所有点,检查是否在多边形内
  442. gd.data[0].x.forEach((xVal, i) => {
  443. const yVal = gd.data[0].y[i];
  444. if (inPolygon(xVal, yVal, xv, yv)) {
  445. const pointKey = `${xVal}-${yVal}`;
  446. if (!addedPoints[pointKey]) {
  447. this.selectedPoints.push({
  448. x: gd.data[0].x[i],
  449. y: gd.data[0].y[i],
  450. time: gd.data[0].timedata[i],
  451. });
  452. newColors[i] = "red"; // 高亮选择的点
  453. newSize[i] = 10; // 设置点的大小
  454. addedPoints[pointKey] = true;
  455. }
  456. }
  457. });
  458. }
  459. // 更新选中点的颜色和大小
  460. this.selectedPoints.forEach((point) => {
  461. newColors[point.index] = "red";
  462. newSize[point.index] = 10;
  463. });
  464. Plotly.addTraces(gd, {
  465. x: this.selectedPoints.map((p) => p.x),
  466. y: this.selectedPoints.map((p) => p.y),
  467. mode: "markers",
  468. type: "scattergl",
  469. marker: {
  470. color: "red",
  471. size: 10,
  472. },
  473. name: "选中点",
  474. showlegend: false,
  475. });
  476. // 处理选中的数据
  477. this.getSelectData(this.selectedPoints, gd.layout);
  478. });
  479. },
  480. handleClearSelect(gd) {
  481. this.selectedPoints = [];
  482. Plotly.restyle(gd, {
  483. "marker.color": [this.originalColors],
  484. "marker.size": [this.originalSizes],
  485. });
  486. },
  487. getSelectData(selectedPoints, layout) {
  488. // 在这里处理选中的数据,您可以将其展示或导出等
  489. console.log("选中的点数据:", selectedPoints);
  490. console.log("布局信息:", layout);
  491. },
  492. handleDownloadCSV(gd) {
  493. if (this.selectedPoints.length === 0) {
  494. alert("没有选中的数据,请选择数据后进行文件下载。");
  495. return;
  496. }
  497. this.downloadCSV();
  498. },
  499. async downloadCSV() {
  500. try {
  501. const paramValueTypes = await axios.get("/ETLapi/sysConf/getByType", {
  502. params: { type: "en_cn_mapping" },
  503. });
  504. // 使用 Set 或 Map 去重
  505. const uniquePoints = [];
  506. this.selectedPoints.forEach((point) => {
  507. if (!uniquePoints.some((p) => p.x === point.x && p.y === point.y)) {
  508. uniquePoints.push(point);
  509. }
  510. });
  511. const newTimedata = uniquePoints.map((item) => item.time);
  512. const result = await axios.post(
  513. "/ETLapi/dataTransfer/getWindTurbineAndTimestamps",
  514. {
  515. timestamps: [...newTimedata],
  516. transferType: this.chartData.scada || "", //分析数据源类型
  517. windFarmCode: this.chartData.field_code || "", //风场编号
  518. windTurbineNumber: this.chartData.data[0].engineCode || "", //风机编号
  519. }
  520. );
  521. const allData = result?.data?.datas || [];
  522. if (!allData.length) {
  523. console.warn("无数据返回");
  524. return;
  525. }
  526. const firstItem = allData[0];
  527. // 4. 获取可用映射字段
  528. const mapping = paramValueTypes?.data?.datas || [];
  529. const matchedMapping = mapping.filter((m) =>
  530. firstItem.hasOwnProperty(m.paramKey)
  531. );
  532. // 5. 构建 CSV 表头(中文)
  533. const headers = matchedMapping.map((m) => m.paramValue).join(",");
  534. // 6. 构建 CSV 内容行
  535. const rows = allData.map((item) => {
  536. return matchedMapping.map((m) => item[m.paramKey] ?? "").join(",");
  537. });
  538. // 7. 合并为 CSV 字符串
  539. const csvString = [headers, ...rows].join("\n");
  540. // 8. 下载
  541. const blob = new Blob([csvString], { type: "text/csv; charset=utf-8" });
  542. const url = URL.createObjectURL(blob);
  543. const a = document.createElement("a");
  544. a.href = url;
  545. a.download = "selected_data.csv";
  546. document.body.appendChild(a);
  547. a.click();
  548. document.body.removeChild(a);
  549. URL.revokeObjectURL(url);
  550. } catch (err) {
  551. console.error(err);
  552. }
  553. },
  554. updateChartColor(color) {
  555. // 更新图表颜色
  556. // this.color1 = color;
  557. this.drawChart();
  558. },
  559. },
  560. };
  561. </script>
  562. <style scoped>
  563. /* 自定义样式 */
  564. </style>