如何基于JSON文件指定列使用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 intoPositive,Negative, andNeutral:// 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 hardcodedvaluesandlabelsin 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, usefetch()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

