如何在@nivo/条形图中显示 0 值,或者如果值是来自 api 的 0,是否有任何方法可以显示无数据标签

问题描述

我想在 Nivo 条形图上显示 0 值,当值为 0 时,它现在显示任何一条线,有什么方法可以在条形图中显示 0 值。如果图形线上的值为零,我们如何添加无数据标签

Graph Image

在上图链接中,Budget and Quality Assurance百分比为0,我想在这一行不显示数据标签

代码如下:

<ResponsiveBar
    data={this.state.compComparisonDataDivisionWiseDMEApi.data}
    keys={this.state.compComparisonDataDivisionWiseDMEApi.keys}
    indexBy="type"
    margin={{ top: 100,right: 0,bottom: 60,left: 100 }}
    padding={0.3}
    innerPadding={10}
    label={d => `${d.value}%`}
    // onClick={e => this.barChartClicked(e)}
    groupMode="grouped"
    colors={["#3d1f42","#542b5a","#68366f","#93519c","#68356f","#93519c"]}
    layout="vertical"
    enableGridY={false}
    defs={[
        {
            id: 'dots',type: 'patternDots',background: 'inherit',color: '#38bcb2',size: 4,padding: 1,stagger: true
        },{
            id: 'lines',type: 'patternLines',color: '#eed312',rotation: -45,linewidth: 6,spacing: 10
        }
    ]}
    fill={[
        {
            match: {
                id: 'fries'
            },id: 'dots'
        },{
            match: {
                id: 'sandwich'
            },id: 'lines'
        }
    ]}
    borderColor={{ from: 'color',modifiers: [['darker',1.6]] }}
    axisTop={null}
    axisRight={null}
    axisBottom={{
        tickSize: 5,tickPadding: 5,tickRotation: 0,legend: '',legendPosition: 'middle',legendOffset: 50
    }}
    axisLeft={{
        tickSize: 5,legendOffset: -60
    }}
    labelSkipwidth={12}
    labelSkipHeight={12}
    labelTextColor={{ from: 'color',1.6]] }}
    legends={[
        {
            dataFrom: 'keys',anchor: 'top-right',direction: 'column',justify: false,translateX: -100,translateY: -100,itemsspacing: 2,itemWidth: 150,itemHeight: 25,itemDirection: 'left-to-right',itemOpacity: 0.85,symbolSize: 20,effects: [
                {
                    on: 'hover',style: {
                        itemOpacity: 1
                    }
                }
            ]
        }
    ]}
    animate={true}
    motionStiffness={90}
    motiondamping={15}
/>

解决方法

在最新版本的@nivo/bar(此时为0.67.0)中,没有过滤掉值为0的bar。使用零值,您将拥有:

enter image description here

要仅针对值为 0 的标签向上移动标签,您可以覆盖 label 属性:

<ResponsiveBar
    .....
    label={(d) =>
        d.value === 0 ? <tspan y="-15">{d.value}</tspan> : d.value
    }
    .....
/>

给出:

enter image description here

Sandbox