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

求助:基于问卷提交生成的文本文件数据制作饼图

Hey Shawn, great job getting the file I/O working for your survey tool—turning that text data into a pie chart is totally doable, let’s walk through it with practical examples.

First, let’s assume your text file has a simple, consistent format (if yours is different, we can adjust!). For example, survey_results.txt might look like this:

非常满意:25
满意:40
一般:20
不满意:10
非常不满意:5

Option 1: Using Python (matplotlib)

If you’re building this with Python (super common for data visualization), the matplotlib library is perfect for pie charts. Here’s a complete, tested code snippet:

import matplotlib.pyplot as plt

# Step 1: Read and parse your text file data
survey_results = {}
with open('survey_results.txt', 'r', encoding='utf-8') as file:
    for line in file:
        # Clean up the line and skip empty entries
        cleaned_line = line.strip()
        if not cleaned_line:
            continue
        # Split each line into option name and count (adjust the delimiter if your file uses commas/spaces)
        option, count = cleaned_line.split(':')
        # Convert count to integer (critical for plotting!)
        survey_results[option] = int(count)

# Step 2: Prepare data for the pie chart
labels = list(survey_results.keys())
counts = list(survey_results.values())

# Step 3: Generate the pie chart
plt.pie(
    counts,
    labels=labels,
    autopct='%1.1f%%',  # Show percentage values with 1 decimal place
    shadow=True,        # Add a subtle shadow for depth
    startangle=90,      # Rotate the chart so the first slice starts at the top
    colors=['#FF9999', '#66B3FF', '#99FF99', '#FFCC99', '#C2C2F0']  # Custom colors (optional)
)
# Ensure the pie chart is a perfect circle
plt.axis('equal')
# Add a clear title
plt.title('问卷结果统计')
# Display the chart (or save it with plt.savefig('survey_pie.png'))
plt.show()

Option 2: Using JavaScript (Chart.js for front-end display)

If you want to show the pie chart directly in a web browser, Chart.js is a lightweight, easy-to-use library. Here’s how to pull your text file data and render the chart:

<!-- First, add Chart.js to your HTML -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="surveyChart" width="400" height="400"></canvas>

<script>
// Fetch the text file and parse data
fetch('survey_results.txt')
  .then(response => response.text())
  .then(rawText => {
    const surveyData = {};
    const lines = rawText.split('\n');
    
    lines.forEach(line => {
      const cleanedLine = line.trim();
      if (!cleanedLine) return;
      const [option, count] = cleanedLine.split(':');
      surveyData[option] = parseInt(count);
    });

    // Render the pie chart
    const ctx = document.getElementById('surveyChart').getContext('2d');
    new Chart(ctx, {
      type: 'pie',
      data: {
        labels: Object.keys(surveyData),
        datasets: [{
          label: '问卷参与人数',
          data: Object.values(surveyData),
          backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'],
          hoverOffset: 4
        }]
      },
      options: {
        plugins: {
          title: {
            display: true,
            text: '问卷结果统计'
          }
        }
      }
    });
  });
</script>

Key Tips to Avoid Issues

  • Data Type Conversion: Always convert your count values to numbers (int/parseInt)—if you pass strings to the chart library, it’ll break.
  • Handle Edge Cases: Skip empty lines or malformed entries in your text file to prevent errors.
  • Adjust Delimiters: If your text file uses commas (非常满意,25) or spaces (非常满意 25) instead of colons, just change the split(':') part to split(',') or split(' ').

Let me know if your text file has a different format, or if you’re using a specific language/framework—I can tweak this further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:40:34