使用Vue3和Plotly.js绘制动态3D图表的示例代码

当前位置: 电视猫 > JavaScript>
电视猫时间: 2024-07-11 06:59:40

  使用Vue3和Plotly.js绘制动态3D图表的示例代码

Here's an example of how to use Vue 3 and Plotly.js to create a dynamic 3D chart:

HTML
<template>
  <div>
    <div ref="chart" id="chart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as Plotly from 'plotly.js';

const chartRef = ref(null);

onMounted(() => {
  const data = generateData();
  const layout = {
    title: 'Dynamic 3D Chart',
    scene: {
      xaxis: {
        title: 'X Axis',
      },
      yaxis: {
        title: 'Y Axis',
      },
      zaxis: {
        title: 'Z Axis',
      },
    },
  };

  Plotly.newPlot(chartRef.value, data, layout, {
    showEditButton: false, // Hide edit button
    responsive: true, // Auto-resize chart
  });

  setInterval(() => {
    updateData(data);
    Plotly.relayout(chartRef.value, layout); // Update layout
  }, 1000); // Update data every second
});

function generateData() {
  const x = [];
  const y = [];
  const z = [];

  for (let i = 0; i < 50; i++) {
    x.push(Math.random() * 100);
    y.push(Math.random() * 100);
    z.push(Math.sin(2 * Math.PI * i / 10) * 50);
  }

  return [
    {
      type: 'scatter3d',
      x: x,
      y: y,
      z: z,
      mode: 'markers',
      marker: {
        size: 10,
        color: 'rgb(255, 0, 0)',
      },
    },
  ];
}

function updateData(data) {
  const z = data[0].z;

  for (let i = 0; i < z.length; i++) {
    z[i] = Math.sin(2 * Math.PI * i / 10) * 50 + Math.random() * 10;
  }
}
</script>

This code will create a 3D scatter plot with 50 points. The points will move randomly up and down over time. The chart will automatically resize to fit the available space.

Here's a breakdown of the code:

  1. Import Plotly.js: Import the Plotly.js library using import * as Plotly from 'plotly.js';.

  2. Create chart reference: Use ref(null) to create a reference to the chart element.

  3. onMounted hook: The onMounted hook is called when the component is mounted. Inside the hook:

    • Generate initial data using generateData().
    • Create the chart layout using layout.
    • Create the chart using Plotly.newPlot(), passing the chart reference, data, layout, and options.
    • Set up an interval to update the data and layout every second.
  4. generateData() function:

    • Generates random data for the chart.
    • Returns an array of traces, each containing the x, y, and z coordinates of the points.
  5. updateData() function:

    • Updates the z-coordinates of the data.
    • Uses Math.sin() to create a wavy pattern.
    • Adds random noise to the data.

This is a basic example of how to create a dynamic 3D chart with Vue 3 and Plotly.js. You can customize the chart by changing the data, layout, and options. You can also add more features, such as interactivity and animation.

    最新电视剧
    热门电视剧
    影视资讯
    最新剧情排行榜
    最新电视剧剧情