【问题标题】:Customizing Colors of React Native Chart Kit自定义 React Native Chart Kit 的颜色
【发布时间】:2019-07-16 17:31:24
【问题描述】:

已经使用react-native-chart-kit 包为 React Native 应用程序创建了一个基本的折线图/面积图,如下面的代码所示。

问题:我们如何独立改变绘图组件的样式/颜色?如点、线描边、面积、轴、刻度标签等...

chartConfig 中的color 参数发生更改时,它似乎会影响几乎整个图表,包括轴刻度标签、网格线、线图下的区域。

是否可以为图表的每个单独属性定义颜色?

代码:

import { LineChart } from 'react-native-chart-kit';
import { Dimensions} from 'react-native';
const screenWidth = Dimensions.get('window').width

const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [{
    data: [ 20, 45, 28, 80, 99, 43 ],
    color: (opacity = 1) => `rgba(134, 65, 244, ${opacity})`,
    strokeWidth: 2 // optional
}]
}

const chartConfig = {
backgroundGradientFrom: '#fff',
backgroundGradientTo: '#fff',
color: (opacity = 1) => `rgba(63, 143, 244, ${opacity})`,
strokeWidth: 2 // optional, default 3
}

class Test extends Component {
    render() {
        return (
            <LineChart 
                data={data}
                width={screenWidth}
                height={400}
                chartConfig={chartConfig}
            />
        )
    }
}

【问题讨论】:

  • 你有没有发现是否可以设置单个点的样式?
  • @per_jansson 还没有!

标签: javascript reactjs react-native charts react-native-chart-kit


【解决方案1】:

这是我用来创建图表的代码。请参阅“propsForDots”部分来设置数据点的样式。

我知道这只是您寻求定制帮助的一部分,但这是一个开始。

<LineChart
  data={{
      labels: labelArray,
      datasets: [
          {
              data: valueArray
          }
      ]
  }}
  width={Dimensions.get("window").width} // from react-native
  height={220}
  yAxisInterval={1} // optional, defaults to 1
  chartConfig={{
  backgroundColor: "#444",
  backgroundGradientFrom: '#444',
  backgroundGradientTo: '#444',
  decimalPlaces: 2, // optional, defaults to 2dp
  color: (opacity = 1) => `rgba(0, 110, 199, ${opacity})`,
  labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
  style: {
      borderRadius: 16
  },
  propsForDots: {
      r: "6",
      strokeWidth: "2",
      stroke: "#fff"
  }
  }}
  bezier
  style={{
      marginVertical: 8,
      borderRadius: 16
  }}
/>

dots的props中,r为点的半径,stroke width为边框大小,stroke为边框颜色。

我还在尝试这个库,这就是我遇到这个问题的原因。希望这对您和其他可能正在搜索相同内容的人有所帮助。

【讨论】:

    【解决方案2】:

    对于点颜色,我们可以使用 getDotColor 道具,这样我们可以编辑每个点并为每个点定义颜色

    getDotColor 定义点颜色函数,用于计算折线图中点的颜色,取(dataPoint, dataPointIndex)

    getDotColor={(dataPoint, dataPointIndex) => {
    console.log('dataPoint ---->', dataPoint);
    console.log('dataPointIndex --->', dataPointIndex);
    //based on condition we return the color as string
    if (dataPointIndex === 0) return 'red';
    }}
    

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多