TwoDMarkersChart.vue 20 KB

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