如何配置PHP生成的Chart.js折线图:指定轴与数据集
Fixing Your Chart.js Axes and Dataset Setup
Let's adjust your code to match the desired chart configuration where:
- X-axis uses the rates (
40, 60, 80) - Each dataset is a day (
Monday,Tuesday,Wednesday) - Y-axis displays the calculated net profits (
800, 1200, 1600)
Key Issues in the Original Code
- The
$profitarray was being overwritten in each inner loop iteration, so each day only kept the last rate's profit value. - The chart labels were set to days instead of rates, swapping the X-axis with the dataset names.
Corrected Code
$days = ["Monday","Tuesday","Wednesday"]; $rates = [40,60,80]; $profit = []; // Build the profit array correctly with all rate-profit pairs per day foreach($days as $dayName) { $profit[$dayName] = []; // Initialize empty array for the day foreach($rates as $rate) { $netProfit = $rate * 20; $profit[$dayName][$rate] = $netProfit; } } $usersChart = new UserChart; // Set X-axis labels to the rates (matches desired X-axis) $usersChart->labels($rates); // Create a dataset for each day, using profits in rate order foreach($profit as $dayName => $rateProfits) { $data = []; // Ensure data points match the order of X-axis labels foreach($rates as $rate) { $data[] = $rateProfits[$rate]; } $usersChart->dataset($dayName, 'line', collect($data)); }
What This Does
- Proper Profit Array Construction: We initialize an empty array for each day first, then add every rate-profit pair to it, resulting in the exact array structure you specified.
- X-Axis Labels: The chart's labels are now set to
$rates, making the X-axis show40, 60, 80. - Dataset Order: For each day, we explicitly pull profit values in the order of the rates to ensure they align correctly with the X-axis labels.
This will generate a line chart where each line represents a day, plotting the net profits against the corresponding rates on the X-axis.
内容的提问来源于stack exchange,提问作者H M Sadman Haque
相关产品推荐
相关产品推荐

