我正在尝试使用recharts
某些货币的最新汇率添加图表。数据显示正确,但图表始终从 0 开始,并略高于最大值。
图表是正确的,但是它不需要从 0 开始,因为这样做,它几乎是一条线。
这是图表的图片:
我希望它recharts
可以自动计算刻度,因此它会从数据中的最小值以下一点开始,并在最大值上方一点点结束。
这是我的代码:
import React, { useEffect, useState } from "react";
import { StyledCurrencyChart } from "./styles";
import {
AreaChart,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Area,
ResponsiveContainer
} from "recharts";
import useExchangeRateProvider from "../../hooks/useExchangeRateProvider";
import api from "../../services/api";
import theme from "../../styles/customMuiTheme";
import moment from "moment";
function Chart({ data }) {
return (
<ResponsiveContainer width="100%" height={200}>
<AreaChart
width="100%"
height={250}
data={data}
margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
>
<defs>
<linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
<stop
offset="5%"
stopColor={theme.palette.secondary.main}
stopOpacity={0.8}
/>
<stop
offset="95%"
stopColor={theme.palette.secondary.main}
stopOpacity={0}
/>
</linearGradient>
</defs>
<XAxis
dataKey="date"
tickFormatter={formatDate}
style={{ fill: "#ffffff" }}
/>
<YAxis tickFormatter={formatRate} style={{ fill: "#ffffff" }} />
<CartesianGrid
strokeDasharray="3 3"
fill="rgba(255, 255, 255, 0.3)"
/>
<Tooltip />
<Area
type="monotone"
dataKey="rate"
stroke={theme.palette.secondary.main}
fillOpacity={1}
fill="url(#colorUv)"
/>
</AreaChart>
</ResponsiveContainer>
);
}
// function to format date
function formatDate(tickItem) {
return moment(tickItem).format("MMM Do YY");
}
// function to format rate
function formatRate(tickItem) {
return parseFloat(tickItem).toLocaleString("en-US");
}
export default function CurrencyChart() {
// selected country
const exchangeRateProvider = useExchangeRateProvider();
const country = exchangeRateProvider.state.exchangeRateProvider.country;
// state
const [values, setValues] = useState({
loading: true,
error: false,
data: {}
});
// update chart on country change
useEffect(() => {
async function updateChart() {
try {
const { data } = await api.get(
`/public/rates/history/${country}`
);
setValues({ loading: false, error: false, data });
} catch (e) {
setValues({ loading: false, error: true, data: {} });
}
}
updateChart();
}, [country]);
return (
<StyledCurrencyChart>
<Chart data={values.data} />
</StyledCurrencyChart>
);
}
我怎样才能实现它?我尝试在下弄乱interval
和ticks
props<YAxis>
,但我无法让它工作。
提前致谢