import { Doughnut } from 'react-chartjs-2'; import { Chart as ChartJS, ArcElement,…
- User
import { Doughnut } from 'react-chartjs-2'; import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'; import ChartDataLabels from 'chartjs-plugin-datalabels'; import { useRef, useMemo } from 'react'; import html2canvas from 'html2canvas'; import downi from '../assets/downi.png';
// Register all necessary components ChartJS.register(ArcElement, Tooltip, Legend, ChartDataLabels);
function DonutChart({ chartData }) { const chartRef = useRef(null);
const data = useMemo(() => { if (!chartData || !chartData.labels?.length) { return { labels: [], datasets: [] }; } return { labels: chartData.labels, datasets: [ { label: 'Spend', data: chartData.values, backgroundColor: ['#6ECEB2', '#5450E4', '#69B8F7', '#FDBA74', '#F472B6'], borderColor: '#FFFFFF', borderWidth: 2, }, ], }; }, [chartData]);
const options = { responsive: true, maintainAspectRatio: false,
// --- FIX 1: Add padding to the chart layout --- // This ensures Chart.js reserves space within the canvas for the labels // that are drawn outside the donut, preventing them from being cut off. layout: { padding: { top: 20, bottom: 30, // Added extra padding at the bottom specifically for the bottom label left: 20, right: 20, } }, plugins: { legend: { display: false, // Disable default legend }, tooltip: { enabled: true, backgroundColor: '#333', titleColor: '#fff', bodyColor: '#fff', padding: 10, displayColors: false, callbacks: { title: (tooltipItems) => tooltipItems[0].label, label: (tooltipItem) => { const value = tooltipItem.raw || 0; let formattedValue; if (value >= 1000000) { formattedValue = `$${(value / 1000000).toFixed(1)}M`; } else if (value >= 1000) { // Improved formatting for K values formattedValue = `$${(value / 1000).toFixed(0)}K`; } else { // Handle values less than 1000 formattedValue = `$${value.toFixed(0)}`; } return `Spend: ${formattedValue}`; }, }, }, datalabels: { formatter: (value, context) => { const total = context.chart.data.datasets[0].data.reduce((a, b) => a + b, 0); if (total === 0) return ''; const percentage = (value / total * 100); const label = context.chart.data.labels[context.dataIndex]; // --- FIX 2: Lower the threshold --- // Changed from > 2 to > 1 so that smaller slices are more likely to show labels return percentage > 1 ? `${label}: ${percentage.toFixed(0)}%` : ''; }, color: '#000000', // Black font color font: { weight: 'bold', size: 11, // Slightly increased font size for better readability }, anchor: 'end', // Anchor at the end of the arc align: 'end', // Align labels radially outside the arc // --- FIX 3: Reduce the offset --- offset: 5, // Reduced from 10 to keep labels closer to the chart clip: false, // Allow labels to extend beyond the chart drawing area (but still inside the canvas padding) clamp: true, // Ensure the label tries to stay visible if possible padding: 3, // Slightly increased padding textAlign: 'center', // Center-align text backgroundColor: 'rgba(255, 255, 255, 0.8)', // Semi-transparent white background, slightly more opaque borderRadius: 3, // Rounded corners for background }, }, cutout: '65%', // Slightly reduced cutout for smaller chart};
const handleDownload = () => { const chartElement = chartRef.current; if (!chartElement) return;
// Hide download icon using visibility to prevent layout shift const icon = chartElement.querySelector('[data-download-icon]'); if (icon) icon.style.visibility = 'hidden'; html2canvas(chartElement, { backgroundColor: '#ffffff', scale: 2, // Use a higher scale for better resolution }).then((canvas) => { const link = document.createElement('a'); link.download = 'DonutChart.png'; link.href = canvas.toDataURL('image/png'); link.click(); // Restore visibility if (icon) icon.style.visibility = 'visible'; }).catch((error) => { console.error('Error generating image:', error); alert('Failed to download chart as image'); // Restore visibility even on error if (icon) icon.style.visibility = 'visible'; });};
// Check if there's actually any data to display (sum > 0) const hasData = data.datasets.length > 0 && data.datasets[0].data.length > 0 && data.datasets[0].data.some(v => v > 0);
return ( Spend by Category
{/* --- FIX 4: Increase container height --- */} {/* Changed h-40 (160px) to h-56 (224px) to give the canvas more vertical room. */} {/* Added flex-grow in case the parent is taller. */} <div className="h-56 relative flex-grow"> {hasData ? ( <Doughnut data={data} options={options} /> ) : ( <div className="flex items-center justify-center h-full text-gray-500"> No Data Available </div> )} </div> </div>); }
export default DonutChart;
need to add a small color for the particular category as a legend before the actual label to indicate the color
Assistant
Here's the implementation that adds a colored square before each label in the donut chart:
import { Doughnut } from 'react-chartjs-2'; import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'; import ChartDataLabels from 'chartjs-plugin-datalabels'; import { useRef, useMemo } from 'react'; import html2canvas from 'html2canvas'; import downi from '../assets/downi.png'; ChartJS.register(ArcElement, Tooltip, Legend, ChartDataLabels); function DonutChart({ chartData }) { const chartRef = useRef(null); const data = useMemo(() => { if (!chartData || !chartData.labels?.length) { return { labels: [], datasets: [] }; } return { labels: chartData.labels, datasets: [ { label: 'Spend', data: chartData.values, backgroundColor: ['#6ECEB2', '#5450E4', '#69B8F7', '#FDBA74', '#F472B6'], borderColor: '#FFFFFF', borderWidth: 2, }, ], }; }, [chartData]); const options = { responsive: true, maintainAspectRatio: false, layout: { padding: { top: 20, bottom: 30, left: 20, right: 20, } }, plugins: { legend: { display: false, }, tooltip: { enabled: true, backgroundColor: '#333', titleColor: '#fff', bodyColor: '#fff', padding: 10, displayColors: false, callbacks: { title: (tooltipItems) => tooltipItems[0].label, label: (tooltipItem) => { const value = tooltipItem.raw || 0; let formattedValue; if (value >= 1000000) { formattedValue = `$${(value / 1000000).toFixed(1)}M`; } else if (value >= 1000) { formattedValue = `$${(value / 1000).toFixed(0)}K`; } else { formattedValue = `$${value.toFixed(0)}`; } return `Spend: ${formattedValue}`; }, }, }, datalabels: { render: function(args) { const { ctx, dataIndex } = args; const dataset = args.chart.data.datasets[0]; const color = dataset.backgroundColor[dataIndex]; const labelValue = dataset.data[dataIndex]; const total = dataset.data.reduce((a, b) => a + b, 0); const percentage = (labelValue / total * 100).toFixed(0); const categoryLabel = args.chart.data.labels[dataIndex]; // Only render if percentage > 1 if (percentage <= 1) return; // Set up font ctx.font = 'bold 11px sans-serif'; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; // The text we want to display const text = `${categoryLabel}: ${percentage}%`; const textWidth = ctx.measureText(text).width; // Dimensions const squareSize = 10; const gap = 5; const totalWidth = squareSize + gap + textWidth; // Calculate positions (center the whole thing on args.x) const startX = args.x - (totalWidth / 2); const squareX = startX; const textX = startX + squareSize + gap; const squareY = args.y - squareSize / 2; // Draw background rectangle const padding = 3; const bgX = startX - padding; const bgY = args.y - (squareSize / 2) - padding; const bgWidth = totalWidth + padding * 2; const bgHeight = squareSize + padding * 2; // Draw background ctx.fillStyle = 'rgba(255, 255, 255, 0.8)'; ctx.fillRect(bgX, bgY, bgWidth, bgHeight); // Draw colored square ctx.fillStyle = color; ctx.fillRect(squareX, squareY, squareSize, squareSize); // Draw text ctx.fillStyle = '#000000'; ctx.fillText(text, textX, args.y); }, anchor: 'end', align: 'end', offset: 5, clip: false, clamp: true, }, }, cutout: '65%', }; const handleDownload = () => { const chartElement = chartRef.current; if (!chartElement) return; const icon = chartElement.querySelector('[data-download-icon]'); if (icon) icon.style.visibility = 'hidden'; html2canvas(chartElement, { backgroundColor: '#ffffff', scale: 2, }).then((canvas) => { const link = document.createElement('a'); link.download = 'DonutChart.png'; link.href = canvas.toDataURL('image/png'); link.click(); if (icon) icon.style.visibility = 'visible'; }).catch((error) => { console.error('Error generating image:', error); alert('Failed to download chart as image'); if (icon) icon.style.visibility = 'visible'; }); }; const hasData = data.datasets.length > 0 && data.datasets[0].data.length > 0 && data.datasets[0].data.some(v => v > 0); return ( <div className="p-3 bg-white rounded-lg border-1.25 border-grey shadow h-full flex flex-col" ref={chartRef}> <div className="flex justify-between items-center mb-2"> <h3 className="text-sm font-semibold text-black">Spend by Category</h3> <button onClick={handleDownload} className="hover:bg-gray-200 p-1 rounded-full"> <img src={downi} alt="Download Icon" className="w-6 h-6 object-contain" data-download-icon /> </button> </div> <div className="h-56 relative flex-grow"> {hasData ? ( <Doughnut data={data} options={options} /> ) : ( <div className="flex items-center justify-center h-full text-gray-500"> No Data Available </div> )} </div> </div> ); } export default DonutChart;This implementation adds a colored square before each label in the donut chart, where the color of the square matches the color of the corresponding segment in the chart. The labels are displayed outside the donut, and each label is now preceded by a small colored square that visually indicates which category the label belongs to.
The key changes made are:
- Replaced the formatter function in the datalabels configuration with a custom render function
- The render function draws a colored square followed by the label text
- The entire label (square + text) is properly centered and has a white background with padding
- The color of the square matches the color of the corresponding segment in the chart
- The rest of the chart's functionality remains unchanged
This solution provides a clear visual indicator of which color corresponds to which category in the chart's labels.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.