TwoDMarkersChart.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <template>
  2. <div style="width: 100%; height: 500px">
  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. :style="getOptionStyle(scheme.colors)"
  19. ></el-option>
  20. </el-select>
  21. <span style="margin-left: 10px">自定义颜色</span>
  22. </div>
  23. <!-- 图表类型切换按钮 -->
  24. <div>
  25. <el-button size="small" @click="setChartType('scatter')"
  26. >散点图</el-button
  27. >
  28. <el-button size="small" @click="setChartType('line')">折线图</el-button>
  29. </div>
  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. <div
  46. v-loading="loading"
  47. :ref="'plotlyChart-' + index"
  48. style="width: 100%; height: 450px"
  49. >
  50. <el-empty v-if="isError" description="请求失败"></el-empty>
  51. </div>
  52. </div>
  53. </template>
  54. <script>
  55. import Plotly from "plotly.js-dist";
  56. import axios from "axios";
  57. import { myMixin } from "@/mixins/chartRequestMixin";
  58. import { colorSchemes } from "@/views/overview/js/colors";
  59. export default {
  60. props: {
  61. fileAddr: {
  62. default: "",
  63. type: String,
  64. },
  65. index: {
  66. type: String,
  67. },
  68. },
  69. data() {
  70. return {
  71. pointSize: 5, // 默认点大小
  72. color1: colorSchemes[0].colors, // 默认颜色
  73. // 配色方案列表(每个方案是一个颜色数组)
  74. colorSchemes: [...colorSchemes],
  75. chartData: {},
  76. chartType: "scatter", // 初始化为散点图 (scatter)
  77. // color1: "", // 默认颜色
  78. selectedPoints: [],
  79. originalColors: [],
  80. originalSizes: [],
  81. };
  82. },
  83. mixins: [myMixin],
  84. async mounted() {
  85. this.getData();
  86. },
  87. methods: {
  88. // 根据配色方案设置每个选项的样式
  89. getOptionStyle(scheme) {
  90. return {
  91. background: `linear-gradient(to right, ${scheme.join(", ")})`,
  92. color: "#fff",
  93. height: "30px",
  94. lineHeight: "30px",
  95. borderRadius: "4px",
  96. };
  97. },
  98. async getData() {
  99. if (this.fileAddr !== "") {
  100. try {
  101. this.loading = true;
  102. this.cancelToken = axios.CancelToken.source();
  103. const resultChartsData = await axios.get(this.fileAddr, {
  104. cancelToken: this.cancelToken.token,
  105. });
  106. if (typeof resultChartsData.data === "string") {
  107. let dataString = resultChartsData.data;
  108. // 如果数据字符串的开头和结尾可能有多余的字符(比如非法字符),可以进行清理
  109. dataString = dataString.trim(); // 去除前后空格
  110. // 如果数据包含了类似 "Infinity" 或其他无法解析的字符,替换它们
  111. dataString = dataString.replace(/Infinity/g, '"Infinity"'); // 例如,将 "Infinity" 转换为字符串
  112. try {
  113. const parsedData = JSON.parse(dataString);
  114. this.chartData = parsedData;
  115. } catch (error) {
  116. console.error("JSON 解析失败:", error);
  117. }
  118. } else {
  119. this.chartData = resultChartsData.data;
  120. }
  121. this.drawChart();
  122. this.isError = false;
  123. this.loading = false;
  124. } catch (error) {
  125. this.isError = true;
  126. this.loading = false;
  127. }
  128. }
  129. },
  130. // 清理非法字符(如换行符等)
  131. cleanJsonString(jsonString) {
  132. return jsonString.replace(/[\n\r\t]/g, "").replace(/,\s*([\]}])/g, "$1"); // 清理换行符等
  133. },
  134. drawChart() {
  135. if (!this.$refs[`plotlyChart-${this.index}`]) {
  136. return false;
  137. }
  138. const data = this.chartData.data && this.chartData.data[0];
  139. let trace = {};
  140. // 保存原始颜色和大小
  141. this.originalColors = [...data.yData];
  142. this.originalSizes = new Array(data.xData.length).fill(6); // 初始点大小
  143. if (this.chartType === "scatter") {
  144. // 绘制 2D 散点图
  145. console.log("重新绘制图表", this.color1);
  146. trace = {
  147. x: data.xData,
  148. y: data.yData,
  149. mode: "markers",
  150. type: "scattergl", // 这里改为 scattergl
  151. text: data.engineName, // 提示文本
  152. marker: {
  153. color: data.yData, // 根据 yData 的值设置颜色
  154. // colorscale: "Viridis", // 使用的颜色区间
  155. colorscale: this.color1
  156. ? [
  157. [0, "#F9FDD2"], // 颜色从 this.color1 开始
  158. [1, this.color1], // 结束颜色为其他颜色
  159. ]
  160. : [
  161. [0, "#F9FDD2"],
  162. [0.15, "#E9F6BD"],
  163. [0.3, "#C2E3B9"],
  164. [0.45, "#8AC8BE"],
  165. [0.6, "#5CA8BF"],
  166. [0.75, "#407DB3"],
  167. [0.9, "#2E4C9A"],
  168. [1, "#1B2973"],
  169. ],
  170. colorbar: {
  171. title: data.colorbartitle, // 色标标题
  172. },
  173. size: new Array(data.xData.length).fill(this.pointSize), // 点的大小
  174. },
  175. hovertemplate:
  176. `${this.chartData.xaixs}:` +
  177. ` %{x} <br> ` +
  178. `${this.chartData.yaixs}:` +
  179. "%{y} <br> <extra></extra>",
  180. // customdata: data.colorbar || data.color, // 将格式化后的时间存入 customdata
  181. };
  182. } else if (this.chartType === "line") {
  183. // 折线图
  184. trace = {
  185. x: data.xData,
  186. y: data.yData,
  187. mode: "lines",
  188. type: "scattergl", // 折线图
  189. text: data.engineName,
  190. line: {
  191. color: this.color1, // 使用自定义颜色
  192. },
  193. };
  194. } else if (this.chartType === "bar") {
  195. // 柱状图
  196. trace = {
  197. x: data.xData,
  198. y: data.yData,
  199. type: "bar", // 柱状图
  200. marker: {
  201. color: this.color1, // 使用自定义颜色
  202. },
  203. };
  204. }
  205. // 图表布局;
  206. const layout = {
  207. title: data.title,
  208. xaxis: {
  209. title: this.chartData.xaixs,
  210. gridcolor: "rgb(255,255,255)", // 网格线颜色
  211. tickcolor: "rgb(255,255,255)",
  212. backgroundcolor: "#e5ecf6",
  213. showbackground: true, // 显示背景
  214. },
  215. yaxis: {
  216. title: this.chartData.yaixs,
  217. gridcolor: "rgb(255,255,255)", // 网格线颜色
  218. tickcolor: "rgb(255,255,255)",
  219. backgroundcolor: "#e5ecf6",
  220. showbackground: true, // 显示背景
  221. },
  222. showlegend: false,
  223. plot_bgcolor: "#e5ecf6",
  224. gridcolor: "#fff", // 设置网格线颜色
  225. // plot_bgcolor: "rad",
  226. // gridcolor: "#d3d3d3", // 设置网格线颜色
  227. };
  228. const config = {
  229. modeBarButtonsToAdd: [
  230. {
  231. name: "选择",
  232. icon: Plotly.Icons.pencil,
  233. click: (gd) => this.handleSelectClick(gd),
  234. },
  235. {
  236. name: "清除选中",
  237. icon: Plotly.Icons.undo,
  238. click: (gd) => this.handleClearSelect(gd),
  239. },
  240. {
  241. name: "下载CSV文件",
  242. icon: Plotly.Icons.disk,
  243. click: (gd) => this.handleDownloadCSV(gd),
  244. },
  245. ],
  246. modeBarButtonsToRemove: [
  247. // 移除不需要的工具按钮
  248. "lasso2d",
  249. ],
  250. displaylogo: false,
  251. editable: true,
  252. scrollZoom: false,
  253. };
  254. // 使用 Plotly 绘制图表
  255. Plotly.react(
  256. this.$refs[`plotlyChart-${this.index}`],
  257. [trace],
  258. layout,
  259. config
  260. ).then(() => {
  261. // 确保在图表加载完成后设置工具栏按钮
  262. const plotElement = this.$refs[`plotlyChart-${this.index}`];
  263. Plotly.relayout(plotElement, layout); // 使用 relayout 来确保自定义按钮应用
  264. });
  265. },
  266. handleSelectClick(gd) {
  267. // 绑定 plotly_click 事件
  268. gd.on("plotly_click", (data) => {
  269. const pointIndex = data.points[0].pointIndex;
  270. const xClick = data.points[0].x;
  271. const yClick = data.points[0].y;
  272. // 将点击的点添加到选中的点数组
  273. this.selectedPoints.push({
  274. x: xClick, // 点击点的 x 坐标
  275. y: yClick, // 点击点的 y 坐标
  276. index: pointIndex, // 点击点的索引
  277. time: data.points[0].text, // 点击点的时间信息
  278. });
  279. // 初始化颜色和大小数组
  280. let newColors = [...this.originalColors];
  281. let newSize = [...this.originalSizes];
  282. // 如果选中的点数大于等于3,进行多边形选择区域的处理
  283. if (this.selectedPoints.length >= 3) {
  284. const xv = this.selectedPoints.map((p) => p.x);
  285. const yv = this.selectedPoints.map((p) => p.y);
  286. // 判断点是否在多边形内
  287. function inPolygon(x, y, xv, yv) {
  288. let inside = false;
  289. for (let i = 0, j = xv.length - 1; i < xv.length; j = i++) {
  290. const intersect =
  291. yv[i] > y !== yv[j] > y &&
  292. x < ((xv[j] - xv[i]) * (y - yv[i])) / (yv[j] - yv[i]) + xv[i];
  293. if (intersect) inside = !inside;
  294. }
  295. return inside;
  296. }
  297. // 用于跟踪已添加的 (x, y) 组合
  298. const addedPoints = {};
  299. // 遍历图表数据中的所有点,检查是否在多边形内
  300. gd.data[0].x.forEach((xVal, i) => {
  301. const yVal = gd.data[0].y[i];
  302. if (inPolygon(xVal, yVal, xv, yv)) {
  303. const pointKey = `${xVal}-${yVal}`;
  304. if (!addedPoints[pointKey]) {
  305. this.selectedPoints.push({
  306. x: gd.data[0].x[i],
  307. y: gd.data[0].y[i],
  308. time: gd.data[0].text[i],
  309. });
  310. newColors[i] = "red"; // 高亮选择的点
  311. newSize[i] = 10; // 设置点的大小
  312. addedPoints[pointKey] = true;
  313. }
  314. }
  315. });
  316. }
  317. // 更新选中点的颜色和大小
  318. this.selectedPoints.forEach((point) => {
  319. newColors[point.index] = "red";
  320. newSize[point.index] = 10;
  321. });
  322. // 使用 Plotly.restyle 更新颜色和大小
  323. Plotly.restyle(gd, {
  324. "marker.color": [newColors],
  325. "marker.size": [newSize],
  326. });
  327. // 处理选中的数据
  328. this.getSelectData(this.selectedPoints, gd.layout);
  329. });
  330. },
  331. handleClearSelect(gd) {
  332. this.selectedPoints = [];
  333. Plotly.restyle(gd, {
  334. "marker.color": [this.originalColors],
  335. "marker.size": [this.originalSizes],
  336. });
  337. },
  338. getSelectData(selectedPoints, layout) {
  339. // 在这里处理选中的数据,您可以将其展示或导出等
  340. console.log("选中的点数据:", selectedPoints);
  341. console.log("布局信息:", layout);
  342. },
  343. handleDownloadCSV(gd) {
  344. if (this.selectedPoints.length === 0) {
  345. alert("没有选中的数据");
  346. return;
  347. }
  348. this.downloadCSV();
  349. },
  350. downloadCSV() {
  351. const headers = [this.chartData.xaixs, this.chartData.yaixs];
  352. const csvRows = [headers]; // 保存标头
  353. // 使用 Set 或 Map 去重
  354. const uniquePoints = [];
  355. this.selectedPoints.forEach((point) => {
  356. if (!uniquePoints.some((p) => p.x === point.x && p.y === point.y)) {
  357. uniquePoints.push(point);
  358. }
  359. });
  360. // 将去重后的点加入 CSV 数据
  361. uniquePoints.forEach((point) => {
  362. csvRows.push(`${point.x},${point.y}`);
  363. });
  364. const csvString = csvRows.join("\n");
  365. const blob = new Blob([csvString], { type: "text/csv; charset=utf-8" });
  366. const url = URL.createObjectURL(blob);
  367. const a = document.createElement("a");
  368. a.href = url;
  369. a.download = "selected_data.csv";
  370. a.click();
  371. URL.revokeObjectURL(url);
  372. },
  373. setChartType(type) {
  374. // 切换图表类型
  375. this.chartType = type;
  376. this.drawChart(); // 重新绘制图表
  377. },
  378. updateChartColor(color) {
  379. // 更新图表颜色
  380. // this.color1 = color;
  381. console.log(this.color1, "this.color1");
  382. this.drawChart();
  383. },
  384. },
  385. };
  386. </script>
  387. <style scoped></style>