TwoDMarkersChart1.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. <!--
  2. * @Author: your name
  3. * @Date: 2024-09-11 14:32:12
  4. * @LastEditTime: 2025-07-10 14:07:08
  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. };
  263. }
  264. if (lineData) {
  265. // 绘制折线图
  266. lineTrace = {
  267. x: lineData.xData, // 线数据的 xData
  268. y: lineData.yData, // 线数据的 yData
  269. mode: "lines+markers", // 线和点同时显示
  270. type: "scattergl", // 使用 scattergl 类型
  271. text: lineData.engineName, // 提示文本
  272. line: {
  273. color: "red", // 线条颜色
  274. },
  275. };
  276. }
  277. // 图表布局
  278. const layout = {
  279. title: {
  280. text: data.title,
  281. font: {
  282. size: 16, // 设置标题字体大小(默认 16)
  283. weight: "bold",
  284. },
  285. },
  286. xaxis: {
  287. title: this.chartData.xaixs,
  288. tickmode: "linear",
  289. gridcolor: "rgb(255,255,255)",
  290. showgrid: true,
  291. zeroline: false,
  292. tickcolor: "rgb(255,255,255)",
  293. backgroundcolor: "#e5ecf6",
  294. showbackground: true, // 显示背景
  295. dtick: 1,
  296. },
  297. yaxis: {
  298. title: this.chartData.yaixs,
  299. gridcolor: "rgb(255,255,255)", // 网格线颜色
  300. tickcolor: "rgb(255,255,255)",
  301. backgroundcolor: "#e5ecf6",
  302. showbackground: true, // 显示背景
  303. },
  304. showlegend: false,
  305. plot_bgcolor: "#e5ecf6",
  306. gridcolor: "#fff", // 设置网格线颜色
  307. };
  308. const getChartSetUp = (axisTitle) => {
  309. return this.setUpImgData.find((item) => item.text.includes(axisTitle));
  310. };
  311. const xChartSetUp = getChartSetUp(layout.xaxis.title);
  312. if (xChartSetUp) {
  313. layout.xaxis.dtick = xChartSetUp.dtick;
  314. layout.xaxis.range = [xChartSetUp.min, xChartSetUp.max];
  315. }
  316. const yChartSetUp = getChartSetUp(layout.yaxis.title);
  317. if (yChartSetUp) {
  318. layout.yaxis.dtick = yChartSetUp.dtick;
  319. layout.yaxis.range = [yChartSetUp.min, yChartSetUp.max];
  320. }
  321. // 配置工具栏按钮
  322. const config = {
  323. modeBarButtonsToAdd: [
  324. {
  325. name: "选择",
  326. icon: Plotly.Icons.pencil,
  327. click: (gd) => this.handleSelectClick(gd),
  328. },
  329. {
  330. name: "清除选中",
  331. icon: Plotly.Icons.undo,
  332. click: (gd) => this.handleClearSelect(gd),
  333. },
  334. {
  335. name: "下载CSV文件",
  336. icon: Plotly.Icons.disk,
  337. click: (gd) => this.handleDownloadCSV(gd),
  338. },
  339. ],
  340. modeBarButtonsToRemove: [
  341. "lasso2d", // 移除不需要的工具按钮
  342. // 移除不需要的工具按钮
  343. "lasso2d",
  344. "sendDataToCloud",
  345. "resetCameraLastSave3d",
  346. "resetCameraDefault3d",
  347. "resetCameraLastSave",
  348. "sendDataToCloud",
  349. "zoom2d", // 缩放按钮
  350. "zoom3d",
  351. "plotlylogo2D",
  352. "plotlylogo3D",
  353. ],
  354. displaylogo: false,
  355. editable: true,
  356. scrollZoom: false,
  357. };
  358. // 合并散点和折线图的数据
  359. const traces = [];
  360. if (scatterTrace) traces.push(scatterTrace); // 如果有散点数据
  361. if (lineTrace) traces.push(lineTrace); // 如果有线图数据
  362. this.$nextTick(() => {
  363. // 使用 Plotly 绘制图表
  364. Plotly.react(
  365. this.$refs[`plotlyChart-${this.index}`], // 这里是对 DOM 元素的引用
  366. traces,
  367. layout,
  368. config
  369. ).then(() => {
  370. // 确保图表加载完成后设置工具栏按钮
  371. const plotElement = this.$refs[`plotlyChart-${this.index}`];
  372. Plotly.relayout(plotElement, layout).then(function (gd) {
  373. // 获取工具栏按钮
  374. const toolbar = gd.querySelector(".modebar");
  375. const buttons = toolbar.querySelectorAll(".modebar-btn");
  376. // 定义一个映射对象,方便修改按钮提示
  377. const titleMap = {
  378. "Download plot as a png": "保存图片",
  379. Autoscale: "缩放",
  380. Pan: "平移",
  381. "Zoom out": "放大",
  382. "Zoom in": "缩小",
  383. "Box Select": "选择框操作",
  384. "Lasso Select": "套索选择操作",
  385. "Reset axes": "重置操作",
  386. "Reset camera to default": "重置相机视角",
  387. "Turntable rotation": "转台式旋转",
  388. "Orbital rotation": "轨道式旋转",
  389. };
  390. // 遍历所有按钮,修改它们的 title
  391. buttons.forEach(function (button) {
  392. const dataTitle = button.getAttribute("data-title");
  393. // 如果标题匹配,修改属性值
  394. if (titleMap[dataTitle]) {
  395. button.setAttribute("data-title", titleMap[dataTitle]);
  396. }
  397. });
  398. }); // 使用 relayout 来确保自定义按钮应用
  399. });
  400. });
  401. },
  402. handleSelectClick(gd) {
  403. // 绑定 plotly_click 事件
  404. gd.on("plotly_click", (data) => {
  405. const pointIndex = data.points[0].pointIndex;
  406. const xClick = data.points[0].x;
  407. const yClick = data.points[0].y;
  408. // 将点击的点添加到选中的点数组
  409. this.selectedPoints.push({
  410. x: xClick, // 点击点的 x 坐标
  411. y: yClick, // 点击点的 y 坐标
  412. index: pointIndex, // 点击点的索引
  413. time: data.points[0].text, // 点击点的时间信息
  414. });
  415. // 初始化颜色和大小数组
  416. let newColors = [...this.originalColors];
  417. let newSize = [...this.originalSizes];
  418. // 如果选中的点数大于等于3,进行多边形选择区域的处理
  419. if (this.selectedPoints.length >= 3) {
  420. const xv = this.selectedPoints.map((p) => p.x);
  421. const yv = this.selectedPoints.map((p) => p.y);
  422. // 判断点是否在多边形内
  423. function inPolygon(x, y, xv, yv) {
  424. let inside = false;
  425. for (let i = 0, j = xv.length - 1; i < xv.length; j = i++) {
  426. const intersect =
  427. yv[i] > y !== yv[j] > y &&
  428. x < ((xv[j] - xv[i]) * (y - yv[i])) / (yv[j] - yv[i]) + xv[i];
  429. if (intersect) inside = !inside;
  430. }
  431. return inside;
  432. }
  433. // 用于跟踪已添加的 (x, y) 组合
  434. const addedPoints = {};
  435. // 遍历图表数据中的所有点,检查是否在多边形内
  436. gd.data[0].x.forEach((xVal, i) => {
  437. const yVal = gd.data[0].y[i];
  438. if (inPolygon(xVal, yVal, xv, yv)) {
  439. const pointKey = `${xVal}-${yVal}`;
  440. if (!addedPoints[pointKey]) {
  441. this.selectedPoints.push({
  442. x: gd.data[0].x[i],
  443. y: gd.data[0].y[i],
  444. time: gd.data[0].text[i],
  445. });
  446. newColors[i] = "red"; // 高亮选择的点
  447. newSize[i] = 10; // 设置点的大小
  448. addedPoints[pointKey] = true;
  449. }
  450. }
  451. });
  452. }
  453. // // 更新选中点的颜色和大小
  454. this.selectedPoints.forEach((point) => {
  455. newColors[point.index] = "red";
  456. newSize[point.index] = 10;
  457. });
  458. Plotly.addTraces(gd, {
  459. x: this.selectedPoints.map((p) => p.x),
  460. y: this.selectedPoints.map((p) => p.y),
  461. mode: "markers",
  462. type: "scattergl",
  463. marker: {
  464. color: "red",
  465. size: 10,
  466. },
  467. name: "选中点",
  468. showlegend: false,
  469. });
  470. // 处理选中的数据
  471. this.getSelectData(this.selectedPoints, gd.layout);
  472. });
  473. },
  474. handleClearSelect(gd) {
  475. this.selectedPoints = [];
  476. Plotly.restyle(gd, {
  477. "marker.color": [this.originalColors],
  478. "marker.size": [this.originalSizes],
  479. });
  480. },
  481. getSelectData(selectedPoints, layout) {
  482. // 在这里处理选中的数据,您可以将其展示或导出等
  483. console.log("选中的点数据:", selectedPoints);
  484. console.log("布局信息:", layout);
  485. },
  486. handleDownloadCSV(gd) {
  487. if (this.selectedPoints.length === 0) {
  488. alert("没有选中的数据,请选择数据后进行文件下载。");
  489. return;
  490. }
  491. this.downloadCSV();
  492. },
  493. downloadCSV() {
  494. const headers = [this.chartData.xaixs, this.chartData.yaixs];
  495. const csvRows = [headers]; // 保存标头
  496. // 使用 Set 或 Map 去重
  497. const uniquePoints = [];
  498. this.selectedPoints.forEach((point) => {
  499. if (!uniquePoints.some((p) => p.x === point.x && p.y === point.y)) {
  500. uniquePoints.push(point);
  501. }
  502. });
  503. // 将去重后的点加入 CSV 数据
  504. uniquePoints.forEach((point) => {
  505. csvRows.push(`${point.x},${point.y}`);
  506. });
  507. const csvString = csvRows.join("\n");
  508. const blob = new Blob([csvString], { type: "text/csv; charset=utf-8" });
  509. const url = URL.createObjectURL(blob);
  510. const a = document.createElement("a");
  511. a.href = url;
  512. a.download = "selected_data.csv";
  513. a.click();
  514. URL.revokeObjectURL(url);
  515. },
  516. updateChartColor(color) {
  517. // 更新图表颜色
  518. // this.color1 = color;
  519. this.drawChart();
  520. },
  521. },
  522. };
  523. </script>
  524. <style scoped>
  525. /* 自定义样式 */
  526. </style>