reactjs React,对来自不同数据源的Rechart中的X轴标签进行排序

b09cbbtk  于 2023-03-01  发布在  React
关注(0)|答案(2)|浏览(153)

我需要帮助计算如何排序X轴标签值在升序重新图表。目前,图表的数据是从两个来源。
下面是代码。

const series = [
  { name: 'SourceA: ', data: reportsFromSourceA },
  { name: 'SourceB: ', data: reportsFromSourceB },
]

const selectedCategories= [...]

 selectedCategories.map((category, i) => (
    <ResponsiveContainer height={350} width='50%' key={category}>
      <LineChart
        margin={{ top: 40, right: 30, left: 70, bottom: 5 }}
        syncId='category'
      >
        <XAxis dataKey='hour' allowDuplicatedCategory={false} />
        <YAxis
          label={{
            value: category,
            position: 'top',
            fontSize: 18,
            offset: 20,
            fontWeight: 'bold',
            fill: COLORS[i % 8]
          }}
          tickFormatter={formatUSD}
        />
        <CartesianGrid strokeDasharray='3 3' />
        <Tooltip formatter={formatUSD} />
        {series.map((s, i) => (
          <Line dataKey='rpc' stroke={COLORS[i % 2]} data={s.data[category]} name={s.name} key={s.name} />
        ))}
        <ReferenceArea y2={0} stroke='red' color='red' strokeOpacity={0.5} />
      </LineChart>
    </ResponsiveContainer>
  )))

szqfcxe2

szqfcxe21#

出现此问题是因为第一个数据源中缺少一些标签条目,而第二个数据源中有。简单的解决方案是仅为标签创建一个额外的数据源,我们不会为该数据源绘制一条线。
相关的沙箱示例是here
完整说明为here
以下解决方案可以解决此问题

const labelSeries = {data: [
  {category: 01}, {category: 05}, {category: 09}, {category: 10}, {category: 11},
  {category: 12}, {category: 13}, {category: 14},{category: 15}, {category: 16},
  {category: 17}, {category: 18}, {category: 19}, {category: 20}, {category: 21},
  {category: 22}
]}

const series = [
  { name: 'SourceA: ', data: reportsFromSourceA },
  { name: 'SourceB: ', data: reportsFromSourceB },
]

const selectedCategories= [...]

 selectedCategories.map((category, i) => (
    <ResponsiveContainer height={350} width='50%' key={category}>
      <LineChart
        margin={{ top: 40, right: 30, left: 70, bottom: 5 }}
        syncId='category'
      >
        <XAxis dataKey='hour' allowDuplicatedCategory={false} />
        <YAxis
          label={{
            value: category,
            position: 'top',
            fontSize: 18,
            offset: 20,
            fontWeight: 'bold',
            fill: COLORS[i % 8]
          }}
          tickFormatter={formatUSD}
        />
        <CartesianGrid strokeDasharray='3 3' />
        <Tooltip formatter={formatUSD} />
        <Line data={labelSeries.data} /> // This line will sort the x-axis label
        {series.map((s, i) => (
          <Line dataKey='rpc' stroke={COLORS[i % 2]} data={s.data[category]} name={s.name} key={s.name} />
        ))}
        <ReferenceArea y2={0} stroke='red' color='red' strokeOpacity={0.5} />
      </LineChart>
    </ResponsiveContainer>
  )))
kiayqfof

kiayqfof2#

我也遇到过类似的问题,但解决方法是:

  • 首先整理来自数据库的数据
  • 或按键值对整个数组排序(升序或降序)

相关问题