You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于JSON文件指定列使用Plotly绘制饼图?

How to Generate a Pie Chart from JSON Data Using Plotly

Got it, let's walk through how to adjust your existing Plotly code to use the polarity and Tweet Type columns from your JSON file. Here's a step-by-step breakdown with working code:

  • Step 1: Define or Load Your JSON Data
    First, let's assume your JSON data follows a structure like this (tweak to match your actual data):

    // Example JSON data (replace with your actual data—could be fetched from a file too)
    const tweetData = [
      { polarity: 1, "Tweet Type": "Positive", user: "user1" },
      { polarity: 4, "Tweet Type": "Negative", user: "user2" },
      { polarity: 0, "Tweet Type": "Neutral", user: "user3" },
      { polarity: 1, "Tweet Type": "Positive", user: "user4" },
      { polarity: 0, "Tweet Type": "Neutral", user: "user5" },
      // ... more entries
    ];
    

    If your JSON is in a separate file, you'll need to fetch it first (using fetch() or a library like Axios)—we'll cover that later.

  • Step 2: Calculate Tweet Type Counts
    Pie charts need numerical values for each category, so we'll count how many tweets fall into Positive, Negative, and Neutral:

    // Count occurrences of each Tweet Type
    const typeCounts = tweetData.reduce((counts, tweet) => {
      const tweetType = tweet["Tweet Type"];
      counts[tweetType] = (counts[tweetType] || 0) + 1;
      return counts;
    }, {});
    
    // Extract labels and values for the chart
    const chartLabels = Object.keys(typeCounts);
    const chartValues = Object.values(typeCounts);
    

    This gives us an object where keys are the tweet types and values are their respective counts.

  • Step 3: Update Your Plotly Code
    Now swap out the hardcoded values and labels in your original code with our dynamic data:

    var data = [{
      values: chartValues, // Use our calculated tweet type counts
      labels: chartLabels, // Use the actual Tweet Type categories
      type: 'pie',
      // Optional: Add polarity-themed colors for clarity
      marker: {
        colors: ['#27ae60', '#e74c3c', '#95a5a6'] // Green = Positive, Red = Negative, Gray = Neutral
      }
    }];
    
    var layout = {
      height: 400,
      width: 500,
      title: 'Tweet Sentiment Distribution' // Add a clear title
    };
    
    Plotly.newPlot('myDiv', data, layout);
    
  • Bonus: Fetching JSON from a File
    If your data is stored in a separate JSON file, use fetch() to load it before generating the chart:

    fetch('your-tweet-data.json')
      .then(response => response.json())
      .then(tweetData => {
        // Run the count calculation and Plotly code here
        const typeCounts = tweetData.reduce((counts, tweet) => {
          const tweetType = tweet["Tweet Type"];
          counts[tweetType] = (counts[tweetType] || 0) + 1;
          return counts;
        }, {});
    
        const chartLabels = Object.keys(typeCounts);
        const chartValues = Object.values(typeCounts);
    
        var data = [{ values: chartValues, labels: chartLabels, type: 'pie' }];
        var layout = { height: 400, width: 500 };
        Plotly.newPlot('myDiv', data, layout);
      })
      .catch(error => console.error('Failed to load JSON:', error));
    

内容的提问来源于stack exchange,提问作者Zerry Mirza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:12:20