TwoDMarkersChart1.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. <!--
  2. * @Author: your name
  3. * @Date: 2024-09-11 14:32:12
  4. * @LastEditTime: 2025-03-21 14:53:57
  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. console.log(newval, "newval");
  110. if (newval.length === 0) {
  111. this.color1 = colorSchemes[5].colors;
  112. } else {
  113. this.color1 = newval;
  114. }
  115. this.updateChartColor();
  116. },
  117. deep: true,
  118. },
  119. setUpImgData: {
  120. handler(newType) {
  121. this.drawChart();
  122. },
  123. deep: true,
  124. },
  125. },
  126. async mounted() {
  127. this.getData();
  128. if (this.themeColor.length === 0) {
  129. this.color1 = colorSchemes[5].colors;
  130. } else {
  131. this.color1 = this.themeColor;
  132. }
  133. // console.log(this.color1, colorSchemes[0].colors, "color1");
  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. // 计算比例值
  199. const colors = ticktext.map((item, ind) => {
  200. // 计算比例值(可以根据需要调整映射的数据范围)
  201. const proportion = (tickvals[ind] - minValue) / (maxValue - minValue);
  202. return [
  203. proportion, // 比例值
  204. this.color1[ind], // 对应的颜色
  205. ];
  206. });
  207. // 将时间字符串映射为数字
  208. let colorValues = [];
  209. // data.colorbar.map((date, index) => timeMapping[date]);
  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. // 仅取 this.color1 的前 4 种颜色进行渐变
  216. // const colorStops = [
  217. // this.color1[0],
  218. // this.color1[4],
  219. // this.color1[8],
  220. // this.color1[12],
  221. // ];
  222. // // 计算渐变比例
  223. // const colors = colorStops.map((color, index) => {
  224. // const proportion = index / (colorStops.length - 1); // 计算比例值 (0, 1/3, 2/3, 1)
  225. // return [proportion, color]; // 生成颜色映射
  226. // });
  227. // // 确保至少有 2 个颜色,否则使用默认颜色
  228. // if (colors.length < 2) {
  229. // colors.push([1, colorStops[colorStops.length - 1] || "#1B2973"]);
  230. // }
  231. // // 计算颜色值映射
  232. // let colorValues = [];
  233. // if (data.colorbar) {
  234. // colorValues = data.colorbar.map((date) => timeMapping[date]);
  235. // } else {
  236. // colorValues = data.color.map((date) => timeMapping[date]);
  237. // }
  238. let scatterTrace = {}; // 用于存放散点图的 trace
  239. let lineTrace = {}; // 用于存放折线图的 trace
  240. // 保存原始颜色和大小
  241. this.originalColors = [...data.yData];
  242. this.originalSizes = new Array(data.xData.length).fill(6); // 初始点大小
  243. // 绘制散点图
  244. if (this.chartType === "scatter") {
  245. scatterTrace = {
  246. x: data.xData,
  247. y: data.yData,
  248. mode: "markers", // 散点
  249. type: "scattergl", // 使用散点图
  250. text: data.engineName, // 提示文本
  251. marker: {
  252. color: colorValues, // 使用时间数据来映射颜色
  253. colorscale: this.color1
  254. ? [...colors]
  255. : [
  256. [0, "#F9FDD2"],
  257. [0.15, "#E9F6BD"],
  258. [0.3, "#C2E3B9"],
  259. [0.45, "#8AC8BE"],
  260. [0.6, "#5CA8BF"],
  261. [0.75, "#407DB3"],
  262. [0.9, "#2E4C9A"],
  263. [1, "#1B2973"],
  264. ], // 默认颜色渐变
  265. colorbar: {
  266. title: data.colorbartitle, // 色标标题
  267. tickvals: tickvals, // 设置刻度值
  268. ticktext: ticktext, // 设置刻度文本
  269. tickmode: "array", // 使用数组模式
  270. tickangle: -45, // 可选:调整刻度文本的角度
  271. },
  272. size: new Array(data.xData.length).fill(this.pointSize), // 点的大小
  273. },
  274. hovertemplate:
  275. `${this.chartData.xaixs}:` +
  276. ` %{x} <br> ` +
  277. `${this.chartData.yaixs}:` +
  278. "%{y} <br>" +
  279. `时间: %{customdata}<extra></extra>`, // 在 hover 中显示格式化后的时间
  280. customdata: data.colorbar || data.color, // 将格式化后的时间存入 customdata
  281. };
  282. }
  283. if (lineData) {
  284. // 绘制折线图
  285. lineTrace = {
  286. x: lineData.xData, // 线数据的 xData
  287. y: lineData.yData, // 线数据的 yData
  288. mode: "lines+markers", // 线和点同时显示
  289. type: "scattergl", // 使用 scattergl 类型
  290. text: lineData.engineName, // 提示文本
  291. line: {
  292. color: "red", // 线条颜色
  293. },
  294. };
  295. }
  296. // 图表布局
  297. const layout = {
  298. title: {
  299. text: data.title,
  300. font: {
  301. size: 16, // 设置标题字体大小(默认 16)
  302. weight: "bold",
  303. },
  304. },
  305. xaxis: {
  306. title: this.chartData.xaixs,
  307. gridcolor: "rgb(255,255,255)", // 网格线颜色
  308. tickcolor: "rgb(255,255,255)",
  309. backgroundcolor: "#e5ecf6",
  310. showbackground: true, // 显示背景
  311. },
  312. yaxis: {
  313. title: this.chartData.yaixs,
  314. gridcolor: "rgb(255,255,255)", // 网格线颜色
  315. tickcolor: "rgb(255,255,255)",
  316. backgroundcolor: "#e5ecf6",
  317. showbackground: true, // 显示背景
  318. },
  319. showlegend: false,
  320. plot_bgcolor: "#e5ecf6",
  321. gridcolor: "#fff", // 设置网格线颜色
  322. };
  323. const getChartSetUp = (axisTitle) => {
  324. return this.setUpImgData.find((item) => item.text.includes(axisTitle));
  325. };
  326. const xChartSetUp = getChartSetUp(layout.xaxis.title);
  327. if (xChartSetUp) {
  328. layout.xaxis.dtick = xChartSetUp.dtick;
  329. layout.xaxis.range = [xChartSetUp.min, xChartSetUp.max];
  330. }
  331. const yChartSetUp = getChartSetUp(layout.yaxis.title);
  332. if (yChartSetUp) {
  333. layout.yaxis.dtick = yChartSetUp.dtick;
  334. layout.yaxis.range = [yChartSetUp.min, yChartSetUp.max];
  335. }
  336. // 配置工具栏按钮
  337. const config = {
  338. modeBarButtonsToAdd: [
  339. {
  340. name: "选择",
  341. icon: Plotly.Icons.pencil,
  342. click: (gd) => this.handleSelectClick(gd),
  343. },
  344. {
  345. name: "清除选中",
  346. icon: Plotly.Icons.undo,
  347. click: (gd) => this.handleClearSelect(gd),
  348. },
  349. {
  350. name: "下载CSV文件",
  351. icon: Plotly.Icons.disk,
  352. click: (gd) => this.handleDownloadCSV(gd),
  353. },
  354. ],
  355. modeBarButtonsToRemove: [
  356. "lasso2d", // 移除不需要的工具按钮
  357. ],
  358. displaylogo: false,
  359. editable: true,
  360. scrollZoom: false,
  361. };
  362. // 合并散点和折线图的数据
  363. const traces = [];
  364. if (scatterTrace) traces.push(scatterTrace); // 如果有散点数据
  365. if (lineTrace) traces.push(lineTrace); // 如果有线图数据
  366. this.$nextTick(() => {
  367. // 使用 Plotly 绘制图表
  368. Plotly.react(
  369. this.$refs[`plotlyChart-${this.index}`], // 这里是对 DOM 元素的引用
  370. traces,
  371. layout,
  372. config
  373. ).then(() => {
  374. // 确保图表加载完成后设置工具栏按钮
  375. const plotElement = this.$refs[`plotlyChart-${this.index}`];
  376. Plotly.relayout(plotElement, layout); // 使用 relayout 来确保自定义按钮应用
  377. });
  378. });
  379. },
  380. handleSelectClick(gd) {
  381. // 绑定 plotly_click 事件
  382. gd.on("plotly_click", (data) => {
  383. const pointIndex = data.points[0].pointIndex;
  384. const xClick = data.points[0].x;
  385. const yClick = data.points[0].y;
  386. // 将点击的点添加到选中的点数组
  387. this.selectedPoints.push({
  388. x: xClick, // 点击点的 x 坐标
  389. y: yClick, // 点击点的 y 坐标
  390. index: pointIndex, // 点击点的索引
  391. time: data.points[0].text, // 点击点的时间信息
  392. });
  393. // 初始化颜色和大小数组
  394. let newColors = [...this.originalColors];
  395. let newSize = [...this.originalSizes];
  396. // 如果选中的点数大于等于3,进行多边形选择区域的处理
  397. if (this.selectedPoints.length >= 3) {
  398. const xv = this.selectedPoints.map((p) => p.x);
  399. const yv = this.selectedPoints.map((p) => p.y);
  400. // 判断点是否在多边形内
  401. function inPolygon(x, y, xv, yv) {
  402. let inside = false;
  403. for (let i = 0, j = xv.length - 1; i < xv.length; j = i++) {
  404. const intersect =
  405. yv[i] > y !== yv[j] > y &&
  406. x < ((xv[j] - xv[i]) * (y - yv[i])) / (yv[j] - yv[i]) + xv[i];
  407. if (intersect) inside = !inside;
  408. }
  409. return inside;
  410. }
  411. // 用于跟踪已添加的 (x, y) 组合
  412. const addedPoints = {};
  413. // 遍历图表数据中的所有点,检查是否在多边形内
  414. gd.data[0].x.forEach((xVal, i) => {
  415. const yVal = gd.data[0].y[i];
  416. if (inPolygon(xVal, yVal, xv, yv)) {
  417. const pointKey = `${xVal}-${yVal}`;
  418. if (!addedPoints[pointKey]) {
  419. this.selectedPoints.push({
  420. x: gd.data[0].x[i],
  421. y: gd.data[0].y[i],
  422. time: gd.data[0].text[i],
  423. });
  424. newColors[i] = "red"; // 高亮选择的点
  425. newSize[i] = 10; // 设置点的大小
  426. addedPoints[pointKey] = true;
  427. }
  428. }
  429. });
  430. }
  431. // 更新选中点的颜色和大小
  432. this.selectedPoints.forEach((point) => {
  433. newColors[point.index] = "red";
  434. newSize[point.index] = 10;
  435. });
  436. // 使用 Plotly.restyle 更新颜色和大小
  437. Plotly.restyle(gd, {
  438. "marker.color": [newColors],
  439. "marker.size": [newSize],
  440. });
  441. // 确保选中的点在最上面
  442. const scatterTrace = gd.data[0]; // 原来的散点数据
  443. const selectedTrace = {
  444. x: this.selectedPoints.map((p) => p.x),
  445. y: this.selectedPoints.map((p) => p.y),
  446. mode: "markers",
  447. type: "scattergl",
  448. marker: {
  449. color: "red", // 选中点颜色
  450. size: 10,
  451. },
  452. };
  453. // 合并数据,并保证选中点在最后
  454. const updatedTraces = [scatterTrace, selectedTrace]; // 选中的点 `selectedTrace` 放在最后
  455. // 更新图表
  456. Plotly.react(gd, updatedTraces, gd.layout);
  457. // 处理选中的数据
  458. this.getSelectData(this.selectedPoints, gd.layout);
  459. });
  460. },
  461. handleClearSelect(gd) {
  462. this.selectedPoints = [];
  463. Plotly.restyle(gd, {
  464. "marker.color": [this.originalColors],
  465. "marker.size": [this.originalSizes],
  466. });
  467. },
  468. getSelectData(selectedPoints, layout) {
  469. // 在这里处理选中的数据,您可以将其展示或导出等
  470. console.log("选中的点数据:", selectedPoints);
  471. console.log("布局信息:", layout);
  472. },
  473. handleDownloadCSV(gd) {
  474. if (this.selectedPoints.length === 0) {
  475. alert("没有选中的数据,请选择数据后进行文件下载。");
  476. return;
  477. }
  478. this.downloadCSV();
  479. },
  480. downloadCSV() {
  481. const headers = [this.chartData.xaixs, this.chartData.yaixs];
  482. const csvRows = [headers]; // 保存标头
  483. // 使用 Set 或 Map 去重
  484. const uniquePoints = [];
  485. this.selectedPoints.forEach((point) => {
  486. if (!uniquePoints.some((p) => p.x === point.x && p.y === point.y)) {
  487. uniquePoints.push(point);
  488. }
  489. });
  490. // 将去重后的点加入 CSV 数据
  491. uniquePoints.forEach((point) => {
  492. csvRows.push(`${point.x},${point.y}`);
  493. });
  494. const csvString = csvRows.join("\n");
  495. const blob = new Blob([csvString], { type: "text/csv; charset=utf-8" });
  496. const url = URL.createObjectURL(blob);
  497. const a = document.createElement("a");
  498. a.href = url;
  499. a.download = "selected_data.csv";
  500. a.click();
  501. URL.revokeObjectURL(url);
  502. },
  503. updateChartColor(color) {
  504. // 更新图表颜色
  505. // this.color1 = color;
  506. this.drawChart();
  507. },
  508. },
  509. };
  510. </script>
  511. <style scoped>
  512. /* 自定义样式 */
  513. </style>