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

C3散点图优化:移除非回归散点连线并显示真实回归方程

Solution for Your C3 Chart Optimizations

Hey there! Let's fix those two issues with your C3 chart and get it working exactly how you want. First, let's address a quick pre-requisite: your CSV data format is broken (all rows are mashed together), so we'll start by fixing that so C3 can read the data properly.

1. Fix the CSV Format

Your grades_access.csv has all data points on a single line, which will cause C3 to misinterpret the data. Here's the corrected, properly formatted version:

Access_grade,Chemistry I,Regression
9.85,3.8,4.54
10.64,5.0,5.31
10.0,4.0,4.69
10.92,5.4,5.58
11.69,5.5,6.33
11.79,8.0,6.43
11.03,6.3,5.69
10.47,5.0,5.14
10.1,5.6,4.78
12.13,8.5,6.76
11.94,6.4,6.57
10.96,6.7,5.62
10.45,5.9,5.12
10.45,5.7,5.12
12.62,7.7,7.24
10.19,5.0,4.87

2. Prevent Scatter Points from Being Connected

The issue here is a mismatch between your CSV column name and the data.types configuration. Your CSV uses Chemistry I for the grade data, but your code references Grade (which doesn't exist). Fixing this ensures the scatter points use the correct scatter type (which inherently doesn't draw lines), while the regression line stays as a line type.

3. Calculate & Display the Real Regression Equation

We'll add a helper function to compute the linear regression coefficients (slope m and intercept b) using the least squares method on your actual data. Then we'll inject the calculated values into your equation element instead of using the fake 2 and 1.

Full Corrected Code

// Helper function to calculate linear regression coefficients
function calculateLinearRegression(xValues, yValues) {
    const n = xValues.length;
    let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;

    for (let i = 0; i < n; i++) {
        sumX += xValues[i];
        sumY += yValues[i];
        sumXY += xValues[i] * yValues[i];
        sumX2 += xValues[i] * xValues[i];
    }

    // Calculate slope (m) and intercept (b)
    const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
    const intercept = (sumY - slope * sumX) / n;

    return { slope, intercept };
}

// Load CSV data and generate chart
d3.csv('grades_access.csv').then(data => {
    // Extract x (Access_grade) and y (Chemistry I) values as numbers
    const xValues = data.map(row => parseFloat(row.Access_grade));
    const yValues = data.map(row => parseFloat(row['Chemistry I']));

    // Calculate regression coefficients
    const regression = calculateLinearRegression(xValues, yValues);

    // Generate C3 chart
    var Grade_access = c3.generate({
        bindto: '#grade_access',
        data: {
            url: 'grades_access.csv',
            x: 'Access_grade',
            types: {
                'Chemistry I': 'scatter', // Match CSV column name
                Regression: 'line'
            },
        },
        axis: {
            y: {
                label: { text: "Average grade", position: "outer-middle" },
                min: 1,
                max: 9
            },
            x: {
                label: { text: "Access grade PAU", position: "outer-center" },
                min: 9,
                max: 14
            }
        },
        size: { height: 400, width: 800 },
        zoom: { enabled: true },
        legend: {
            show: true,
            position: 'inset',
            inset: { anchor: 'top-right', x: 20, y: 300 }
        }
    });

    // Display real regression equation (rounded to 2 decimal places for readability)
    document.getElementById("equation").innerHTML = 
        `Grade = ${regression.slope.toFixed(2)}·x + ${regression.intercept.toFixed(2)}`;
});

Key Changes Explained:

  • Fixed CSV Format: Each data point is now on its own line, so C3 parses it correctly.
  • Corrected Data Type Mapping: We now reference 'Chemistry I' (the actual CSV column) for the scatter type, ensuring no lines are drawn between these points.
  • Real Regression Calculation: The calculateLinearRegression function computes the actual slope and intercept using your dataset, and we display these values rounded to 2 decimal places for clarity.
  • Async Data Loading: We use d3.csv() (which C3 relies on under the hood) to load the data first, so we can calculate the regression before rendering the equation.

When you run this, you'll see:

  • Blue scatter points with no connecting lines
  • An orange regression line as intended
  • A real regression equation based on your actual data

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:46:42