TwoDMarkersChart1.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import puppeteer from "puppeteer";
  2. import fs from "fs-extra";
  3. import path from "path";
  4. import FormData from "form-data";
  5. import { colorSchemes } from "../colors.js";
  6. export const generateTwoDMarkersChart1 = async (data) => {
  7. try {
  8. // 创建临时目录
  9. const tempDir = path.join(process.cwd(), "images");
  10. await fs.ensureDir(tempDir);
  11. const tempFilePath = path.join(
  12. tempDir,
  13. `temp_scatter_chart_${Date.now()}.png`
  14. );
  15. // 获取 plotly.js 的绝对路径
  16. const plotlyPath = path.join(
  17. process.cwd(),
  18. "src",
  19. "public",
  20. "js",
  21. "plotly-3.0.1.min.js"
  22. );
  23. const plotlyContent = await fs.readFile(plotlyPath, "utf-8");
  24. // 创建浏览器实例
  25. const browser = await puppeteer.launch({
  26. headless: "new",
  27. args: ["--no-sandbox", "--disable-setuid-sandbox"],
  28. });
  29. try {
  30. const page = await browser.newPage();
  31. // 提取散点数据和线数据
  32. const scatterData = data.data.filter(
  33. (item) => item.engineName !== "合同功率曲线"
  34. )[0]; // 点数据
  35. const lineData = data.data.filter(
  36. (item) =>
  37. item.engineName === "合同功率曲线" ||
  38. item.enginName === "合同功率曲线"
  39. )[0]; // 线数据
  40. // 提取唯一时间标签,并计算 tickvals 和 ticktext
  41. const uniqueTimeLabels = scatterData.colorbar
  42. ? [...new Set(scatterData.colorbar)]
  43. : [...new Set(scatterData.color)];
  44. const tickvals = uniqueTimeLabels.map((_, index) => index + 1);
  45. const ticktext = uniqueTimeLabels.map((dateStr) => {
  46. const date = new Date(dateStr);
  47. return date.toLocaleDateString("en-CA", {
  48. year: "numeric",
  49. month: "2-digit",
  50. });
  51. });
  52. const timeMapping = uniqueTimeLabels.reduce((acc, curr, index) => {
  53. acc[curr] = index + 1;
  54. return acc;
  55. }, {});
  56. // 计算颜色值映射
  57. let colorValues = scatterData.colorbar
  58. ? scatterData.colorbar.map((date) => timeMapping[date])
  59. : scatterData.color.map((date) => timeMapping[date]);
  60. // 绘制散点图
  61. const scatterTrace = {
  62. x: scatterData.xData,
  63. y: scatterData.yData,
  64. mode: "markers",
  65. type: "scattergl", // 使用 scattergl 提高性能
  66. text: scatterData.engineName, // 提示文本
  67. marker: {
  68. color: colorValues,
  69. colorscale: [
  70. [0, "#F9FDD2"],
  71. [0.15, "#E9F6BD"],
  72. [0.3, "#C2E3B9"],
  73. [0.45, "#8AC8BE"],
  74. [0.6, "#5CA8BF"],
  75. [0.75, "#407DB3"],
  76. [0.9, "#2E4C9A"],
  77. [1, "#1B2973"],
  78. ],
  79. size: new Array(scatterData.xData.length).fill(6), // 点的大小
  80. },
  81. hovertemplate: `${data.xaixs}: %{x} <br> ${data.yaixs}: %{y} <br> 时间: %{customdata}<extra></extra>`,
  82. customdata: scatterData.colorbar || scatterData.color, // 将格式化后的时间存入 customdata
  83. };
  84. // 绘制线图
  85. let lineTrace = {};
  86. if (lineData) {
  87. lineTrace = {
  88. x: lineData.xData,
  89. y: lineData.yData,
  90. mode: "lines+markers", // 线和点同时显示
  91. type: "scattergl", // 使用 scattergl 类型
  92. text: lineData.engineName, // 提示文本
  93. line: {
  94. color: "red", // 线条颜色
  95. },
  96. };
  97. }
  98. console.log(lineData, lineTrace, "2222");
  99. // 图表布局
  100. const layout = {
  101. title: {
  102. text: scatterData.title,
  103. font: {
  104. size: 16,
  105. weight: "bold",
  106. },
  107. },
  108. xaxis: {
  109. title: {
  110. text: data.xaixs,
  111. },
  112. gridcolor: "rgb(255,255,255)",
  113. tickcolor: "rgb(255,255,255)",
  114. backgroundcolor: "#e5ecf6",
  115. showbackground: true,
  116. },
  117. yaxis: {
  118. title: {
  119. text: data.yaixs,
  120. },
  121. gridcolor: "rgb(255,255,255)",
  122. tickcolor: "rgb(255,255,255)",
  123. backgroundcolor: "#e5ecf6",
  124. showbackground: true,
  125. },
  126. showlegend: false,
  127. plot_bgcolor: "#e5ecf6",
  128. gridcolor: "#fff",
  129. };
  130. // 准备 HTML 内容
  131. const htmlContent = `
  132. <!DOCTYPE html>
  133. <html>
  134. <head>
  135. <meta charset="UTF-8">
  136. <title>2D 散点图</title>
  137. <script>${plotlyContent}</script>
  138. </head>
  139. <body>
  140. <div id="chart" style="width: 100%; height: 600px"></div>
  141. <script>
  142. const traces = [${JSON.stringify(scatterTrace)}${
  143. lineTrace ? `, ${JSON.stringify(lineTrace)}` : ""
  144. }];
  145. const layout = ${JSON.stringify(layout)};
  146. Plotly.newPlot('chart', traces, layout, { responsive: true }).then(() => {
  147. window.chartRendered = true; // 确保在图表渲染完成后设置
  148. console.log("图表渲染完成");
  149. }).catch((error) => {
  150. console.error("图表渲染错误:", error); // 捕获渲染错误
  151. });
  152. </script>
  153. </body>
  154. </html>
  155. `;
  156. // 设置页面内容
  157. await page.setContent(htmlContent, {
  158. waitUntil: "networkidle0",
  159. });
  160. // 等待图表渲染完成,延长超时时间
  161. await page.waitForFunction(() => window.chartRendered === true, {
  162. timeout: 150000, // 延长到 150 秒
  163. });
  164. // 截图并保存到临时文件
  165. const chartElement = await page.$("#chart");
  166. await chartElement.screenshot({
  167. path: tempFilePath,
  168. type: "png",
  169. });
  170. // 上传图片到服务器
  171. const formData = new FormData();
  172. formData.append("file", fs.createReadStream(tempFilePath));
  173. return formData;
  174. } catch (error) {
  175. console.error("生成2D散点图失败:", error);
  176. throw error;
  177. } finally {
  178. await browser.close();
  179. }
  180. } catch (error) {
  181. console.error("生成2D散点图失败:", error);
  182. throw error;
  183. }
  184. };