Generating a Responsive Bar Chart with Nivo
Explains how to create a responsive bar chart using Nivo's ResponsiveBar component, ensuring the chart adjusts its size based on the container's dimensions.
import { ResponsiveBar } from '@nivo/bar';
import React from 'react';
Import the ResponsiveBar component from the @nivo/bar package and React for component creation.
const data = [
{
'country': 'Germany',
'hot dog': 60,
'hot dogColor': 'hsl(66, 70%, 50%)',
'burger': 40,
'burgerColor': 'hsl(347, 70%, 50%)'
},
// Add more data points as needed
];
Define the data for the bar chart. Each object represents a group (e.g., country) with keys for each bar (e.g., hot dog, burger) and optional color.
const MyResponsiveBarChart = () => (
<div style={{ height: '400px' }}>
<ResponsiveBar
data={data}
keys={['hot dog', 'burger']}
indexBy='country'
margin={{ top: 50, right: 130, bottom: 50, left: 60 }}
padding={0.3}
valueScale={{ type: 'linear' }}
indexScale={{ type: 'band', round: true }}
colors={{ scheme: 'nivo' }}
borderColor={{ from: 'color', modifiers: [['darker', 1.6]] }}
axisTop={null}
axisRight={null}
axisBottom={{
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: 'country',
legendPosition: 'middle',
legendOffset: 32
}}
axisLeft={{
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: 'food',
legendPosition: 'middle',
legendOffset: -40
}}
labelSkipWidth={12}
labelSkipHeight={12}
labelTextColor={{ from: 'color', modifiers: [['darker', 1.6]] }}
animate={true}
motionStiffness={90}
motionDamping={15}
/>
</div>
);
Create a React functional component that renders a responsive bar chart using the ResponsiveBar component. The chart's size adjusts based on the div container's height.
export default MyResponsiveBarChart;
Export the MyResponsiveBarChart component for use in other parts of the application.