TwoDMarkersChart1.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. <!--
  2. * @Author: your name
  3. * @Date: 2024-09-11 14:32:12
  4. * @LastEditTime: 2025-07-14 13:39: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: 600px">
  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: 500px"
  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[5].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[5].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[5].colors;
  130. // } else {
  131. // this.color1 = this.themeColor;
  132. // }
  133. });
  134. // console.log(this.color1, colorSchemes[0].colors, "color1");
  135. },
  136. methods: {
  137. // 根据配色方案设置每个选项的样式
  138. getOptionStyle(scheme) {
  139. return {
  140. background: `linear-gradient(to right, ${scheme
  141. .slice(0, 8)
  142. .join(", ")})`,
  143. color: "#fff",
  144. height: "30px",
  145. lineHeight: "30px",
  146. borderRadius: "0px",
  147. };
  148. },
  149. async getData() {
  150. if (this.fileAddr !== "") {
  151. try {
  152. this.loading = true;
  153. this.cancelToken = axios.CancelToken.source();
  154. const resultChartsData = await axios.get(this.fileAddr, {
  155. cancelToken: this.cancelToken.token,
  156. });
  157. this.chartData = resultChartsData.data;
  158. this.drawChart();
  159. this.isError = false;
  160. this.loading = false;
  161. } catch (error) {
  162. this.isError = true;
  163. this.loading = false;
  164. }
  165. }
  166. },
  167. drawChart() {
  168. // 提取散点数据和线数据
  169. const data =
  170. this.chartData.data &&
  171. this.chartData.data.filter(
  172. (item) => item.enginName !== "合同功率曲线"
  173. )[0]; // 点数据
  174. const lineData =
  175. this.chartData.data &&
  176. this.chartData.data.filter(
  177. (item) => item.enginName === "合同功率曲线"
  178. )[0]; // 线数据
  179. // 提取唯一时间标签,并计算 tickvals 和 ticktext
  180. const uniqueTimeLabels = data.colorbar
  181. ? [...new Set(data.colorbar)]
  182. : [...new Set(data.color)]; // 从 colorbar 中提取唯一的时间标签
  183. // console.log(data.colorbar, "data.colorbar 1");
  184. const tickvals = uniqueTimeLabels.map((label, index) => index + 1); // 根据时间标签生成 tickvals
  185. const ticktext = uniqueTimeLabels.map((dateStr) => {
  186. const date = new Date(dateStr);
  187. return date.toLocaleDateString("en-CA", {
  188. year: "numeric",
  189. month: "2-digit",
  190. }); // 格式化为 'yyyy-MM'
  191. }); // 使用格式化后的时间作为 ticktext
  192. const timeMapping = uniqueTimeLabels.reduce((acc, curr, index) => {
  193. acc[curr] = index + 1;
  194. return acc;
  195. }, {});
  196. // 获取 yData 的最小值和最大值来做比例值的计算
  197. const minValue = Math.min(...tickvals);
  198. const maxValue = Math.max(...tickvals);
  199. // 计算比例值
  200. const colors = ticktext.map((item, ind) => {
  201. // 计算比例值(可以根据需要调整映射的数据范围)
  202. const proportion = (tickvals[ind] - minValue) / (maxValue - minValue);
  203. return [
  204. proportion, // 比例值
  205. this.color1[ind], // 对应的颜色
  206. ];
  207. });
  208. // 将时间字符串映射为数字
  209. let colorValues = [];
  210. if (data.colorbar) {
  211. colorValues = data.colorbar.map((date, index) => timeMapping[date]);
  212. } else {
  213. colorValues = data.color.map((date, index) => timeMapping[date]);
  214. }
  215. let scatterTrace = {}; // 用于存放散点图的 trace
  216. let lineTrace = {}; // 用于存放折线图的 trace
  217. // 保存原始颜色和大小
  218. this.originalColors = [...data.yData];
  219. this.originalSizes = new Array(data.xData.length).fill(6); // 初始点大小
  220. // 绘制散点图
  221. if (this.chartType === "scatter") {
  222. scatterTrace = {
  223. x: data.xData,
  224. y: data.yData,
  225. mode: "markers", // 散点
  226. type: "scattergl", // 使用散点图
  227. text: data.engineName, // 提示文本
  228. marker: {
  229. color: colorValues, // 使用时间数据来映射颜色
  230. colorscale: this.color1
  231. ? [...colors]
  232. : [
  233. [0, "#F9FDD2"],
  234. [0.15, "#E9F6BD"],
  235. [0.3, "#C2E3B9"],
  236. [0.45, "#8AC8BE"],
  237. [0.6, "#5CA8BF"],
  238. [0.75, "#407DB3"],
  239. [0.9, "#2E4C9A"],
  240. [1, "#1B2973"],
  241. ], // 默认颜色渐变
  242. colorbar: {
  243. title: data.colorbartitle, // 色标标题
  244. tickvals: tickvals, // 设置刻度值
  245. ticktext: ticktext, // 设置刻度文本
  246. tickmode: "array", // 使用数组模式、
  247. x: 1.05, // x 控制横向位置(1 是右边,>1 就更靠右)
  248. y: 1.04, // y=1 是顶部
  249. // len: 0.4, // 高度(0~1之间)
  250. xanchor: "left", // x锚点从左对齐
  251. yanchor: "top", // y锚点从顶部对齐
  252. },
  253. size: new Array(data.xData.length).fill(this.pointSize), // 点的大小
  254. },
  255. hovertemplate:
  256. `${this.chartData.xaixs}:` +
  257. ` %{x} <br> ` +
  258. `${this.chartData.yaixs}:` +
  259. "%{y} <br>" +
  260. `时间: %{customdata}<extra></extra>`, // 在 hover 中显示格式化后的时间
  261. customdata: data.colorbar || data.color, // 将格式化后的时间存入 customdata
  262. timedata: data.timeData,
  263. };
  264. }
  265. if (lineData) {
  266. // 绘制折线图
  267. lineTrace = {
  268. x: lineData.xData, // 线数据的 xData
  269. y: lineData.yData, // 线数据的 yData
  270. mode: "lines+markers", // 线和点同时显示
  271. type: "scattergl", // 使用 scattergl 类型
  272. text: lineData.engineName, // 提示文本
  273. line: {
  274. color: "red", // 线条颜色
  275. },
  276. };
  277. }
  278. // 图表布局
  279. const layout = {
  280. title: {
  281. text: data.title,
  282. font: {
  283. size: 16, // 设置标题字体大小(默认 16)
  284. weight: "bold",
  285. },
  286. },
  287. xaxis: {
  288. title: this.chartData.xaixs,
  289. tickmode: "linear",
  290. gridcolor: "rgb(255,255,255)",
  291. showgrid: true,
  292. zeroline: false,
  293. tickcolor: "rgb(255,255,255)",
  294. backgroundcolor: "#e5ecf6",
  295. showbackground: true, // 显示背景
  296. dtick: 1,
  297. },
  298. yaxis: {
  299. title: this.chartData.yaixs,
  300. gridcolor: "rgb(255,255,255)", // 网格线颜色
  301. tickcolor: "rgb(255,255,255)",
  302. backgroundcolor: "#e5ecf6",
  303. showbackground: true, // 显示背景
  304. },
  305. showlegend: false,
  306. plot_bgcolor: "#e5ecf6",
  307. gridcolor: "#fff", // 设置网格线颜色
  308. };
  309. const getChartSetUp = (axisTitle) => {
  310. return this.setUpImgData.find((item) => item.text.includes(axisTitle));
  311. };
  312. const xChartSetUp = getChartSetUp(layout.xaxis.title);
  313. if (xChartSetUp) {
  314. layout.xaxis.dtick = xChartSetUp.dtick;
  315. layout.xaxis.range = [xChartSetUp.min, xChartSetUp.max];
  316. }
  317. const yChartSetUp = getChartSetUp(layout.yaxis.title);
  318. if (yChartSetUp) {
  319. layout.yaxis.dtick = yChartSetUp.dtick;
  320. layout.yaxis.range = [yChartSetUp.min, yChartSetUp.max];
  321. }
  322. // 配置工具栏按钮
  323. const config = {
  324. modeBarButtonsToAdd: [
  325. {
  326. name: "选择",
  327. icon: Plotly.Icons.pencil,
  328. click: (gd) => this.handleSelectClick(gd),
  329. },
  330. {
  331. name: "清除选中",
  332. icon: Plotly.Icons.undo,
  333. click: (gd) => this.handleClearSelect(gd),
  334. },
  335. {
  336. name: "下载CSV文件",
  337. icon: Plotly.Icons.disk,
  338. click: (gd) => this.handleDownloadCSV(gd),
  339. },
  340. ],
  341. modeBarButtonsToRemove: [
  342. "lasso2d", // 移除不需要的工具按钮
  343. // 移除不需要的工具按钮
  344. "lasso2d",
  345. "sendDataToCloud",
  346. "resetCameraLastSave3d",
  347. "resetCameraDefault3d",
  348. "resetCameraLastSave",
  349. "sendDataToCloud",
  350. "zoom2d", // 缩放按钮
  351. "zoom3d",
  352. "plotlylogo2D",
  353. "plotlylogo3D",
  354. ],
  355. displaylogo: false,
  356. editable: true,
  357. scrollZoom: false,
  358. };
  359. // 合并散点和折线图的数据
  360. const traces = [];
  361. if (scatterTrace) traces.push(scatterTrace); // 如果有散点数据
  362. if (lineTrace) traces.push(lineTrace); // 如果有线图数据
  363. this.$nextTick(() => {
  364. // 使用 Plotly 绘制图表
  365. Plotly.react(
  366. this.$refs[`plotlyChart-${this.index}`], // 这里是对 DOM 元素的引用
  367. traces,
  368. layout,
  369. config
  370. ).then(() => {
  371. // 确保图表加载完成后设置工具栏按钮
  372. const plotElement = this.$refs[`plotlyChart-${this.index}`];
  373. Plotly.relayout(plotElement, layout).then(function (gd) {
  374. // 获取工具栏按钮
  375. const toolbar = gd.querySelector(".modebar");
  376. const buttons = toolbar.querySelectorAll(".modebar-btn");
  377. // 定义一个映射对象,方便修改按钮提示
  378. const titleMap = {
  379. "Download plot as a png": "保存图片",
  380. Autoscale: "缩放",
  381. Pan: "平移",
  382. "Zoom out": "放大",
  383. "Zoom in": "缩小",
  384. "Box Select": "选择框操作",
  385. "Lasso Select": "套索选择操作",
  386. "Reset axes": "重置操作",
  387. "Reset camera to default": "重置相机视角",
  388. "Turntable rotation": "转台式旋转",
  389. "Orbital rotation": "轨道式旋转",
  390. };
  391. // 遍历所有按钮,修改它们的 title
  392. buttons.forEach(function (button) {
  393. const dataTitle = button.getAttribute("data-title");
  394. // 如果标题匹配,修改属性值
  395. if (titleMap[dataTitle]) {
  396. button.setAttribute("data-title", titleMap[dataTitle]);
  397. }
  398. });
  399. }); // 使用 relayout 来确保自定义按钮应用
  400. });
  401. });
  402. },
  403. handleSelectClick(gd) {
  404. // 绑定 plotly_click 事件
  405. gd.on("plotly_click", (data) => {
  406. const pointIndex = data.points[0].pointIndex;
  407. const xClick = data.points[0].x;
  408. const yClick = data.points[0].y;
  409. // 将点击的点添加到选中的点数组
  410. this.selectedPoints.push({
  411. x: xClick, // 点击点的 x 坐标
  412. y: yClick, // 点击点的 y 坐标
  413. index: pointIndex, // 点击点的索引
  414. time: data.points[0]?.data?.timedata[data.points[0].pointIndex], // 点击点的时间信息
  415. });
  416. // 初始化颜色和大小数组
  417. let newColors = [...this.originalColors];
  418. let newSize = [...this.originalSizes];
  419. // 如果选中的点数大于等于3,进行多边形选择区域的处理
  420. if (this.selectedPoints.length >= 3) {
  421. const xv = this.selectedPoints.map((p) => p.x);
  422. const yv = this.selectedPoints.map((p) => p.y);
  423. // 判断点是否在多边形内
  424. function inPolygon(x, y, xv, yv) {
  425. let inside = false;
  426. for (let i = 0, j = xv.length - 1; i < xv.length; j = i++) {
  427. const intersect =
  428. yv[i] > y !== yv[j] > y &&
  429. x < ((xv[j] - xv[i]) * (y - yv[i])) / (yv[j] - yv[i]) + xv[i];
  430. if (intersect) inside = !inside;
  431. }
  432. return inside;
  433. }
  434. // 用于跟踪已添加的 (x, y) 组合
  435. const addedPoints = {};
  436. // 遍历图表数据中的所有点,检查是否在多边形内
  437. gd.data[0].x.forEach((xVal, i) => {
  438. const yVal = gd.data[0].y[i];
  439. if (inPolygon(xVal, yVal, xv, yv)) {
  440. const pointKey = `${xVal}-${yVal}`;
  441. if (!addedPoints[pointKey]) {
  442. this.selectedPoints.push({
  443. x: gd.data[0].x[i],
  444. y: gd.data[0].y[i],
  445. time: gd.data[0].text[i],
  446. });
  447. newColors[i] = "red"; // 高亮选择的点
  448. newSize[i] = 10; // 设置点的大小
  449. addedPoints[pointKey] = true;
  450. }
  451. }
  452. });
  453. }
  454. // // 更新选中点的颜色和大小
  455. this.selectedPoints.forEach((point) => {
  456. newColors[point.index] = "red";
  457. newSize[point.index] = 10;
  458. });
  459. Plotly.addTraces(gd, {
  460. x: this.selectedPoints.map((p) => p.x),
  461. y: this.selectedPoints.map((p) => p.y),
  462. mode: "markers",
  463. type: "scattergl",
  464. marker: {
  465. color: "red",
  466. size: 10,
  467. },
  468. name: "选中点",
  469. showlegend: false,
  470. });
  471. // 处理选中的数据
  472. this.getSelectData(this.selectedPoints, gd.layout);
  473. });
  474. },
  475. handleClearSelect(gd) {
  476. this.selectedPoints = [];
  477. Plotly.restyle(gd, {
  478. "marker.color": [this.originalColors],
  479. "marker.size": [this.originalSizes],
  480. });
  481. },
  482. getSelectData(selectedPoints, layout) {
  483. // 在这里处理选中的数据,您可以将其展示或导出等
  484. console.log("选中的点数据:", selectedPoints);
  485. console.log("布局信息:", layout);
  486. },
  487. handleDownloadCSV(gd) {
  488. if (this.selectedPoints.length === 0) {
  489. alert("没有选中的数据,请选择数据后进行文件下载。");
  490. return;
  491. }
  492. this.downloadCSV();
  493. },
  494. async downloadCSV() {
  495. const paramValueTypes = await axios.get("/ETLapi/sysConf/getByType", {
  496. params: { type: "en_cn_mapping" },
  497. });
  498. console.log(paramValueTypes, "paramValueTypes");
  499. const headers = [this.chartData.xaixs, this.chartData.yaixs];
  500. const csvRows = [headers]; // 保存标头
  501. // 使用 Set 或 Map 去重
  502. const uniquePoints = [];
  503. // this.selectedPoints.forEach((point) => {
  504. // if (!uniquePoints.some((p) => p.x === point.x && p.y === point.y)) {
  505. // uniquePoints.push(point);
  506. // }
  507. // });
  508. // // 将去重后的点加入 CSV 数据
  509. // uniquePoints.forEach((point) => {
  510. // csvRows.push(`${point.x},${point.y}`);
  511. // });
  512. // const csvString = csvRows.join("\n");
  513. // const blob = new Blob([csvString], { type: "text/csv; charset=utf-8" });
  514. // const url = URL.createObjectURL(blob);
  515. // const a = document.createElement("a");
  516. // a.href = url;
  517. // a.download = "selected_data.csv";
  518. // a.click();
  519. // URL.revokeObjectURL(url);
  520. },
  521. updateChartColor(color) {
  522. // 更新图表颜色
  523. // this.color1 = color;
  524. this.drawChart();
  525. },
  526. },
  527. };
  528. </script>
  529. <style scoped>
  530. /* 自定义样式 */
  531. </style>