recharts#LabelList TypeScript Examples
The following examples show how to use
recharts#LabelList.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Balances.tsx From abrechnung with GNU Affero General Public License v3.0 | 4 votes |
export default function Balances({ group }) {
const theme: Theme = useTheme();
const isSmallScreen = useMediaQuery(theme.breakpoints.down("sm"));
const history = useHistory();
const personalAccounts = useRecoilValue(personalAccountsSeenByUser(group.id));
const clearingAccounts = useRecoilValue(clearingAccountsSeenByUser(group.id));
const balances = useRecoilValue(accountBalances(group.id));
const [selectedTab, setSelectedTab] = useState("1");
const colorGreen = theme.palette.mode === "light" ? theme.palette.success.light : theme.palette.success.dark;
const colorRed = theme.palette.mode === "light" ? theme.palette.error.light : theme.palette.error.dark;
const colorGreenInverted = theme.palette.mode === "dark" ? theme.palette.success.light : theme.palette.success.dark;
const colorRedInverted = theme.palette.mode === "dark" ? theme.palette.error.light : theme.palette.error.dark;
useTitle(`${group.name} - Balances`);
const chartData = personalAccounts.map((account) => {
return {
name: account.name,
balance: balances[account.id].balance,
totalPaid: balances[account.id].totalPaid,
totalConsumed: balances[account.id].totalConsumed,
id: account.id,
};
});
const unbalancedClearingAccounts = clearingAccounts
.filter((account) => balances[account.id].balance !== 0)
.map((account) => {
return {
name: account.name,
id: account.id,
balance: balances[account.id].balance,
};
});
const chartHeight = Object.keys(balances).length * 30 + 100;
// TODO determine the rendered width of the account names and take the maximum
const yaxiswidth = isSmallScreen
? Math.max(Math.max(...personalAccounts.map((account) => account.name.length)), 20)
: Math.max(...personalAccounts.map((account) => account.name.length)) * 7 + 5;
const handleBarClick = (data, event) => {
const id = data.activePayload[0].payload.id;
history.push(`/groups/${group.id}/accounts/${id}`);
};
return (
<MobilePaper>
<TabContext value={selectedTab}>
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
<TabList onChange={(event, idx) => setSelectedTab(idx)} centered>
<Tab label="Chart" value="1" />
<Tab label="Table" value="2" />
</TabList>
</Box>
<TabPanel value="1" sx={{ padding: { xs: 1, md: 2 } }}>
{personalAccounts.length === 0 && <Alert severity="info">No Accounts</Alert>}
{unbalancedClearingAccounts.length !== 0 && (
<Alert severity="info">
<AlertTitle>Some Clearing Accounts have remaining balances.</AlertTitle>
{unbalancedClearingAccounts.map((account) => (
<Typography variant="body2" key={account.id} component="span">
<>{account.name}:</>
<Typography
variant="body2"
component="span"
sx={{ color: account.balance < 0 ? colorRedInverted : colorGreenInverted }}
>
{account.balance.toFixed(2)} {group.currency_symbol}{" "}
</Typography>
</Typography>
))}
</Alert>
)}
{isSmallScreen ? (
<List>
{personalAccounts.map((account) => (
<>
<ListItemLink key={account.id} to={`/groups/${group.id}/accounts/${account.id}`}>
<ListItemText primary={account.name} />
<Typography
align="right"
variant="body2"
sx={{
color:
balances[account.id].balance < 0
? colorRedInverted
: colorGreenInverted,
}}
>
{balances[account.id].balance.toFixed(2)} {group.currency_symbol}
</Typography>
</ListItemLink>
<Divider key={account.id * 2} component="li" />
</>
))}
</List>
) : (
<div className="area-chart-wrapper" style={{ width: "100%", height: `${chartHeight}px` }}>
<ResponsiveContainer>
<BarChart
data={chartData}
margin={{
top: 20,
right: 20,
bottom: 20,
left: 20,
}}
layout="vertical"
onClick={handleBarClick}
>
<XAxis
stroke={theme.palette.text.primary}
type="number"
unit={group.currency_symbol}
/>
<YAxis
dataKey="name"
stroke={theme.palette.text.primary}
type="category"
width={yaxiswidth}
/>
<Tooltip
formatter={(label) =>
parseFloat(label).toFixed(2) + ` ${group.currency_symbol}`
}
labelStyle={{
color: theme.palette.text.primary,
}}
itemStyle={{
color: theme.palette.text.primary,
}}
contentStyle={{
backgroundColor: theme.palette.background.paper,
borderColor: theme.palette.divider,
borderRadius: theme.shape.borderRadius,
}}
/>
<Bar dataKey="balance">
{chartData.map((entry, index) => {
return (
<Cell
key={`cell-${index}`}
fill={entry["balance"] >= 0 ? colorGreen : colorRed}
/>
);
})}
<LabelList
dataKey={(entry) =>
`${entry["balance"].toFixed(2)}${group.currency_symbol}`
}
position="insideLeft"
fill={theme.palette.text.primary}
/>
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
)}
</TabPanel>
<TabPanel value="2" sx={{ padding: { xs: 1, md: 2 } }}>
<BalanceTable group={group} />
</TabPanel>
</TabContext>
</MobilePaper>
);
}
Example #2
Source File: index.tsx From korona-info with MIT License | 4 votes |
Index: NextPage<{ groupedCoronaData: GroupedData, hospitalised: HospitalData[] }> = ({
groupedCoronaData, hospitalised
}: {
groupedCoronaData: GroupedData;
hospitalised: HospitalData[];
}) => {
const [selectedHealthCareDistrict, selectHealthCareDistrict] = useState<
string
>('all');
const confirmed = groupedCoronaData[selectedHealthCareDistrict].confirmed;
const deaths = groupedCoronaData[selectedHealthCareDistrict].deaths;
const recovered = groupedCoronaData[selectedHealthCareDistrict].recovered;
const allConfirmed = groupedCoronaData.all.confirmed;
const toast = useToast()
const latestInfection = confirmed.length
? format(
utcToZonedTime(
new Date(confirmed[confirmed.length - 1].date),
timeZone
),
'dd.MM.yyyy - HH:mm',
{ timeZone }
)
: null;
const latestInfectionDistrict =
confirmed[confirmed.length - 1]?.healthCareDistrict;
const latestDeath = deaths.length
? format(
utcToZonedTime(new Date(deaths[deaths.length - 1].date), timeZone),
'd.M.yyyy'
)
: null;
const latestDeathDistrict = deaths.length
? deaths[deaths.length - 1].area
: null;
const latestRecoveredDistrict = recovered.length
? recovered[recovered.length - 1].healthCareDistrict
: null;
const latestRecovered = recovered.length
? format(
utcToZonedTime(
new Date(recovered[recovered.length - 1].date),
timeZone
),
'd.M.yyyy'
)
: null;
const infectionsToday = getInfectionsToday(confirmed);
const [cumulativeChartScale, setCumulativeChartScale] = useState<
'linear' | 'log'
>('linear');
const [forecastChartScale, setForecaseChartScale] = useState<
'linear' | 'log'
>('linear');
// Map data to show development of infections
const {
infectionDevelopmentData,
infectionDevelopmentData30Days
} = groupedCoronaData[selectedHealthCareDistrict].timeSeries;
const maxValues =
infectionDevelopmentData30Days[infectionDevelopmentData30Days.length - 1];
const dataMaxValue = Math.max(
maxValues?.deaths ?? 0,
maxValues?.infections ?? 0,
maxValues?.infections ?? 0
);
const {
infectionsByDistrict,
infectionsByDistrictPercentage,
areas
} = getTnfectionsByDistrict(allConfirmed);
const { infectionsBySourceCountry } = getInfectionsBySourceCountry(confirmed);
const networkGraphData = getNetworkGraphData(confirmed);
const { t } = useContext(UserContext);
const humanizeHealthcareDistrict = (district: string) => {
if (district === 'all') {
return t('All healthcare districts');
} else if (district === 'unknown') {
return t('unknown');
} else {
return district;
}
};
const reversedConfirmed = confirmed
// @ts-ignore
.map((i, index) => ({
index: index + 1,
...i,
healthCareDistrict: humanizeHealthcareDistrict(i.healthCareDistrict)
}))
.reverse();
const humanizedHealthCareDistrict = humanizeHealthcareDistrict(
selectedHealthCareDistrict
);
useEffect(() => {
if (typeof window !== undefined) {
toast({
position: 'bottom',
title: 'Datan lähteenä nyt THL',
description: 'HS:n datan lähde on vaihtunut THL:ään. THL:n tiedotussyklistä johtuen tiedot päivittyvät aiempaa harvemmin. Myös vanhemmissa tapauksissa voi olla päivämääräkohtaisia eroja, johtuen muuttuneesta raportointitavasta.',
status: "info",
isClosable: true,
duration: 14000,
});
}
}, [])
return (
<>
<Head>
<title>
{t('finland corona status')} - {t('cases')} : {confirmed.length || 0}{' '}
- {t('recovered')}: {recovered.length || 0} - {t('deaths')}:{' '}
{deaths.length || 0}
</title>
<meta
name="description"
content={`Suomen koronavirus-tartuntatilanne – tartunnat: ${confirmed.length ||
0} - parantuneet: ${recovered.length ||
0} - menehtyneet: ${deaths.length || 0}`}
/>
<meta property="og:title" content={t('finland corona status')} />
<meta
property="og:description"
content={`Tartuntoja tällä hetkellä: ${confirmed.length ||
0} - parantuneet: ${recovered.length ||
0} - menehtyneet: ${deaths.length || 0}`}
/>
<meta
property="og:site_name"
content="Suomen koronavirus-tartuntatilanne"
/>
<meta property="og:locale" content="fi_FI" />
<meta property="og:type" content="website" />
<meta property="og:image" content="/images/corona-virus.png" />
<meta property="og:image:width" content="1920" />
<meta property="og:image:height" content="1928" />
<meta property="og:url" content="https://korona.kans.io" />
</Head>
<Layout>
<Flex
alignItems="center"
flexDirection="column"
flex="1"
width={'100%'}
maxWidth="1440px"
margin="auto"
>
<Header />
<Flex
flexWrap="wrap"
flexDirection="row"
justifyContent="left"
alignItems="stretch"
flex="1"
width={'100%'}
>
<Box width={['100%', '100%', 1 / 3, 1 / 3]} p={3}>
<Select
value={selectedHealthCareDistrict ?? undefined}
onChange={event => selectHealthCareDistrict(event.target.value)}
>
<option key={'all'} value={'all'}>
{t('All healthcare districts')}
</option>
{healtCareDistricts.map(healthcareDistrict => (
<option
key={healthcareDistrict.name}
value={healthcareDistrict.name}
>
{healthcareDistrict.name}
</option>
))}
))}
</Select>
</Box>
</Flex>
<Flex
flexWrap="wrap"
flexDirection="row"
justifyContent="center"
alignItems="stretch"
flex="1"
width={'100%'}
>
<Box width={['100%', '100%', 1 / 2, 1 / 2]} p={3}>
<Block
title={t('cases') + ` (${humanizedHealthCareDistrict})`}
textAlign="center"
extraInfo={`${t('New cases today')} ${infectionsToday} ${t(
'person'
)}`}
footer={`${t(
'latest case'
)} ${latestInfection} (${humanizeHealthcareDistrict(
latestInfectionDistrict
)})`}
>
<StatBlock
count={confirmed.length}
helpText={`${t('New cases today')}: ${infectionsToday} ${t(
'person'
)}`}
/>
</Block>
</Box>
<Box width={['100%', '100%', 1 / 2, 1 / 2]} p={3}>
<Block
title={t('deaths') + ` (${humanizedHealthCareDistrict})`}
footer={
latestDeath
? `${t(
'last death'
)} ${latestDeath} (${humanizeHealthcareDistrict(
latestDeathDistrict!
)})`
: t('no death')
}
>
<StatBlock count={deaths.length || 0} />
</Block>
</Box>
{/* <Box width={['100%', '100%', 1 / 3, 1 / 3]} p={3}>
<Block
title={t('recovered') + ` (${humanizedHealthCareDistrict})`}
footer={
`${latestRecovered
? `${t(
'latest recovery'
)} ${latestRecovered} (${humanizeHealthcareDistrict(latestRecoveredDistrict!)}).`
: ' '} ${t('recoveredNotice')}`}
>
<StatBlock count={recovered.length || 0} />
</Block>
</Box> */}
<Box width={['100%']} p={3}>
<Block
title={
t('accumulated change') + ` (${humanizedHealthCareDistrict})`
}
footer={t('cases recovered and death in past 30 days')}
>
<ButtonGroup
spacing={0}
alignSelf="center"
display="flex"
justifyContent="center"
marginTop="-15px"
>
<Button
size="xs"
fontFamily="Space Grotesk Regular"
px={3}
letterSpacing="1px"
borderRadius="4px 0px 0px 4px"
borderWidth="0px"
isActive={cumulativeChartScale === 'linear'}
onClick={() => setCumulativeChartScale('linear')}
>
{t('linear')}
</Button>
<Button
size="xs"
fontFamily="Space Grotesk Regular"
px={3}
letterSpacing="1px"
borderRadius="0px 4px 4px 0px"
borderWidth="0px"
isActive={cumulativeChartScale === 'log'}
onClick={() => setCumulativeChartScale('log')}
>
{t('logarithmic')}
</Button>
</ButtonGroup>
<ResponsiveContainer width={'100%'} height={380}>
<ComposedChart
data={
cumulativeChartScale === 'log'
? infectionDevelopmentData30Days.map(zerosToNulls)
: infectionDevelopmentData30Days
}
margin={{ top: 20, right: 30, left: 0, bottom: 30 }}
>
<defs>
<linearGradient
id="colorInfection"
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop
offset="5%"
stopColor={colors[8]}
stopOpacity={0.6}
/>
<stop
offset="95%"
stopColor={colors[8]}
stopOpacity={0}
/>
</linearGradient>
<linearGradient
id="colorRecovered"
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop
offset="5%"
stopColor={colors[7]}
stopOpacity={0.6}
/>
<stop
offset="95%"
stopColor={colors[7]}
stopOpacity={0}
/>
</linearGradient>
<linearGradient
id="colorDeaths"
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop
offset="5%"
stopColor={colors[0]}
stopOpacity={0.6}
/>
<stop
offset="95%"
stopColor={colors[0]}
stopOpacity={0}
/>
</linearGradient>
</defs>
<XAxis
tickFormatter={d => format(new Date(d), 'd.M.')}
tick={<CustomizedAxisTick isDate />}
dataKey="date"
domain={['dataMin', 'dataMax']}
type="number"
scale="time"
/>
<YAxis
scale={cumulativeChartScale}
dataKey="infections"
domain={[
cumulativeChartScale === 'log' ? 1 : 0,
dataMaxValue + 10
]}
unit={' ' + t('person')}
tick={{ fontSize: 12 }}
name={t('cases')}
/>
<CartesianGrid opacity={0.2} />
<Tooltip
labelFormatter={v => format(new Date(v), 'dd.MM.yyyy')}
/>
<Bar
isAnimationActive={false}
fill={colors[1]}
opacity={0.4}
dataKey="infectionsDaily"
name={t('cases of the day')}
unit={' ' + t('person')}
/>
<Area
isAnimationActive={false}
type="monotone"
unit={' ' + t('person')}
name={t('total cases')}
dataKey="infections"
stroke={colors[8]}
fillOpacity={1}
fill="url(#colorInfection)"
/>
{/* <Area
isAnimationActive={false}
type="monotone"
unit={' ' + t('person')}
name={t('total recovered')}
dataKey="recovered"
stroke={colors[7]}
fillOpacity={1}
fill="url(#colorRecovered)"
/> */}
<Area
isAnimationActive={false}
type="monotone"
unit={' ' + t('person')}
name={t('total deaths')}
dataKey="deaths"
stroke={colors[0]}
fillOpacity={1}
fill="url(#colorDeaths)"
/>
<Legend wrapperStyle={{ bottom: '10px' }} />
</ComposedChart>
</ResponsiveContainer>
</Block>
</Box>
{/*
<Box width={['100%']} p={3}>
<Block title="Tartuntojen kumulatiivinen ennustemalli" footer={`Tartuntojen kehityksen ennustemalli 60 päivää. Laskee ennustetun eksponentiaalisen kasvun käyttämällä aiemmin luotuja tietoja. Käytetty <a style="color: #319795;" href="https://github.com/mljs/regression-exponential" target="_blank">exponential-regression</a> kirjastoa.`}>
<ButtonGroup spacing={0} alignSelf="center" display="flex" justifyContent="center" marginTop="-15px">
<Button size="xs" fontFamily="Space Grotesk Regular" px={3} letterSpacing="1px" borderRadius="4px 0px 0px 4px" borderWidth="0px" isActive={forecastChartScale === 'linear'} onClick={() => setForecaseChartScale('linear')}>
Lineaarinen
</Button>
<Button size="xs" fontFamily="Space Grotesk Regular" px={3} letterSpacing="1px" borderRadius="0px 4px 4px 0px" borderWidth="0px" isActive={forecastChartScale === 'log'} onClick={() => setForecaseChartScale('log')}>
Logaritminen
</Button>
</ButtonGroup>
<ResponsiveContainer width={'100%'} height={350}>
<AreaChart
data={prediction60Days}
margin={{ top: 20, right: 30, left: 0, bottom: 20 }}
>
<defs>
<linearGradient id="colorInfection" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={colors[8]} stopOpacity={0.6} />
<stop offset="95%" stopColor={colors[8]} stopOpacity={0} />
</linearGradient>
</defs>
<XAxis tickFormatter={d => format(new Date(d), 'd.M.')} tick={<CustomizedAxisTick isDate />} dataKey="date" domain={['dataMin', 'dataMax']} type="number" scale="time" />
<YAxis scale={forecastChartScale} dataKey="infections" domain={['auto', 'auto']} unit={' ' + t('person') } tick={{ fontSize: 12 }} name="Tartunnat" />
<CartesianGrid opacity={0.2} />
<ReferenceLine
x={today}
stroke="rgba(0,0,0,.5)"
// @ts-ignore
label={{ position: 'top', value: 'Nyt', fill: 'rgba(0,0,0,0.5)', fontSize: 12 }}
strokeDasharray="3 3" />
<Tooltip labelFormatter={v => format(new Date(v), 'dd.MM.yyyy')} />
<Area type="monotone" name="Ennuste" unit={' ' + t('person') } dataKey="infections" stroke={colors[8]} fillOpacity={1} fill="url(#colorInfection)" />
</AreaChart>
</ResponsiveContainer>
</Block>
</Box>
*/}
<Box width={['100%', '100%', '100%', '100%', 1 / 2]} p={3}>
<Block
title={t('Cases by district')}
footer={t('Helsinki metropolitan area is shown as HUS')}
>
<ResponsiveContainer width={'100%'} height={350}>
<BarChart
data={infectionsByDistrict}
margin={{
top: 20,
right: 30,
left: 0,
bottom: 85
}}
>
<XAxis
interval={0}
dataKey="name"
tick={<CustomizedAxisTick />}
/>
<YAxis
yAxisId="left"
unit={' ' + t('person')}
dataKey="infections"
tick={{ fontSize: 12 }}
/>
<Tooltip />
<Bar
isAnimationActive={false}
dataKey="infections"
name={t('cases')}
unit={' ' + t('person')}
yAxisId="left"
>
{areas.map((area, index) => (
<Cell key={area} fill={colors[index % colors.length]} />
))}
<LabelList
dataKey="infections"
position="top"
formatter={e => e}
/>
</Bar>
</BarChart>
</ResponsiveContainer>
</Block>
</Box>
<Box width={['100%', '100%', '100%', '100%', 1 / 2]} p={3}>
<Block
title={t('infectionsPerDisrictAndSize')}
footer={t('infectionsPerDisrictAndSize')}
>
<ResponsiveContainer width={'100%'} height={350}>
<BarChart
data={infectionsByDistrictPercentage}
margin={{
top: 20,
right: 30,
left: 0,
bottom: 85
}}
>
<XAxis
interval={0}
dataKey="name"
tick={<CustomizedAxisTick />}
/>
<YAxis
unit=" %"
dataKey="perDistrict"
tick={{ fontSize: 12 }}
/>
<Tooltip />
<Bar isAnimationActive={false} dataKey="perDistrict" name="%-osuus väestöstä" unit=" %">
{areas.map((area, index) => (
<Cell key={area} fill={colors[index % colors.length]} />
))}
<LabelList
dataKey="perDistict"
position="top"
formatter={e => e}
/>
</Bar>
</BarChart>
</ResponsiveContainer>
</Block>
</Box>
<Box width={['100%', '100%', '100%', '100%', 1 / 2]} p={3}>
<Block
title={t('log') + ` (${humanizedHealthCareDistrict})`}
footer={t('logFooter')}
>
<Table
height={500}
data={reversedConfirmed}
columns={useMemo(() => infectionColumns, [])}
/>
</Block>
</Box>
<BubbleChart data={groupedCoronaData} />
{/* <Box width={['100%', '100%', '100%', '100%', 1 / 2]} p={3}>
<Block
title={
t('infectionNetwork') + ` (${humanizedHealthCareDistrict})`
}
footer={t('infectionNetworkFooter')}
>
<NetworkGraph data={networkGraphData} />
</Block>
</Box> */}
<Box width={['100%']} p={3}>
<Block
title={
t('hospitalizedData') + ` (${t('All healthcare districts')})`
}
>
<ResponsiveContainer width={'100%'} height={350}>
<BarChart
data={hospitalised.slice(Math.max(hospitalised.length - 30, 0))}
margin={{
top: 20,
right: 30,
left: 0,
bottom: 85
}}
>
<XAxis
interval={0}
dataKey="dateString"
tick={<CustomizedAxisTick />}
padding={{ left: 50, right: 50 }}
/>
<YAxis
unit={' ' + t('person')}
dataKey="totalHospitalised"
tick={{ fontSize: 12 }}
/>
<Tooltip />
<Bar
isAnimationActive={false}
stackId="a"
dataKey="inIcu"
name={t("inIcu")}
unit={' ' + t('person')}
fill="#F3858D"
/>
<Bar
isAnimationActive={false}
stackId="a"
dataKey="inWard"
name={t("inWard")}
unit={' ' + t('person')}
fill="#2FAB8E"
/>
<Bar
isAnimationActive={false}
stackId="a"
dataKey="totalHospitalised"
opacity={0}
name={t("inHospital")}
unit={' ' + t('person')}
fill="rgba(0,0,0,1)"
strokeWidth={0}
legendType="none"
/>
<Legend wrapperStyle={{ bottom: '15px' }} />
</BarChart>
</ResponsiveContainer>
</Block>
</Box>
</Flex>
<Copyright />
</Flex>
</Layout>
</>
);
}