首页 > 解决方案 > 如何在 React 原生 svg 图表中添加背景颜色?

问题描述

我正在使用这个包来创建一个自定义的多个LineChart.

我面临的唯一问题是我需要在每个 2 y 值之间添加背景颜色(我确定只有 0 到 4 的值)。所以我必须在“0-1”、“1-2”和“2-3”之间添加一种颜色。

这是当前的结果

在此处输入图像描述

这就是我需要实现的

在此处输入图像描述

这是我的代码

<YAxis
   data={dataAxeY}
   style={{ marginBottom: xAxisHeight }}
   contentInset={verticalContentInset}
   svg={{ fill: "rgba(134, 65, 244, 0.5)", fontSize: 16 }}
   numberOfTicks={4}
 />
<View style={{ flex: 1, marginLeft: 10, borderWidth: 2 }}>
          <LineChart
            yAccessor={({ item }) => item.value}
            xAccessor={({ item }) => item.date}
            style={{ flex: 1 }}
            data={data}
            contentInset={verticalContentInset}
            svg={{
              strokeWidth: 3,
              stroke: "url(#gradient)",
            }}
            svg={{ stroke: "rgb(134, 65, 244)" }}
            curve={shape.curveNatural}
          >

          </LineChart>

          <XAxis
            data={dataAxeX}
            formatLabel={(_, index) => dataAxeX[index].dateName}
            contentInset={{ left: 10, right: 10 }}
            svg={{ fill: "rgba(134, 65, 244, 0.5)" }}
          />
        </View>
      </View>

我试图添加一个Rect我这样指定填充颜色的

const ColoredRect = (({ y }) => (
  <Rect
     x="0"
     y="0"
     width="100%"
     height="33%"
     fill="rgb(0,0,255)"
  />
))

它已添加,但我想要一个更通用的解决方案。

我希望你能帮我解决这个问题。

标签: react-nativereact-native-androidreact-native-svg-charts

解决方案


Starting from the version 5.0, you can now create children SVG to the chart and place it below using belowChart= {true}.

So for example you can do something like this:

<View style={{flex: 1}}>
  <LineChart
    style={{flex: 1}}
    data={yAxisValues}
    yMin={-10}
    yMax={10}
    contentInset={verticalContentInset}
    svg={{
      stroke: strokeColorLeft,
      strokeWidth: '2',
    }}>
    <Svg belowChart={true}>
      <Rect
        x="0"
        y="40%"
        width="100%"
        height="20%"
        fill="rgb(144,238,144,0.3)"
      />
      <Rect
        x="0"
        y="0"
        width="100%"
        height="20%"
        fill="rgb(173,216,230,0.3)"
      />
    </Svg>
    <Grid />
  </LineChart>
  <XAxis
    data={xAxisValues}
    formatLabel={(value, index) => index}
    contentInset={verticalContentInset}
    svg={axesSvg}
  />
</View>

That gives you this result :


推荐阅读