powerMarkers2DCharts.vue 17 KB

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