正負の値を表示するバーチャートの設定で発生しやすい問題と対策を説明します。
YAxisのboundaryGapパラメータをfalseに設定すると、バーがY軸に直接接続され、最上位/最下位のバーがマウスオーバー時に非表示になる問題があります。この設定はtrueに変更するか削除することで解消されます。
ツールチップのz-index設定については、標準のtooltipがz-index:9999999で設定されているため、カスタムポップアップはこれより高い値を指定する必要があります。
XAxisとバーの間隔を調整する場合、boundaryGapをtrueに設定し、axisLabelのpaddingで左側の余白を調整します。例:
xAxis: {
boundaryGap: true,
axisLabel: {
padding: [0, 0, 0, 20]
}
}
ラベルが長すぎる場合の対処法:
- ラベルを30度回転:
rotate: 30 - 縦書き表示:
formatter: (value) => value.split('').join('\n')
nameGapを調整して単位の位置を一致させます。例:
xAxis: {
name: '/月',
nameGap: -10,
nameTextStyle: {
padding: [0, 0, 0, document.getElementById('year_revenue').offsetWidth - 80]
}
}
以下は実装例です。正負の値を異なる色で表示し、未達成値には陰影を適用します。
const totalRevenueChart = echarts.init(document.getElementById('total_revenue'));
const chartConfig = {
tooltip: {
trigger: 'axis',
formatter: params => `${params[0].name}
総収益: ${params[0].value}`
},
grid: { top: '15px', left: '-10px', containLabel: true },
xAxis: { show: false },
yAxis: {
type: 'category',
data: ['現金', '株式', '運用', '証券', 'オプション'],
axisLabel: {
margin: 60,
formatter: (value, index) => `${value} ${[100, 30, 200, -50, 20][index]}`
},
boundaryGap: false
},
series: [
{
type: 'bar',
stack: 'total',
data: [9, 8, -7, 8, 4],
barWidth: '15px',
itemStyle: {
color: params => params.value >= 0 ? '#E82724' : '#00A212'
}
},
{
type: 'bar',
stack: 'total',
data: [0, 1, 0, 1, 5],
barWidth: '15px',
itemStyle: { color: '#E9ECED' }
}
]
};
totalRevenueChart.setOption(chartConfig);
年度収益チャートでは、X軸の単位を適切に配置します:
const yearlyChart = echarts.init(document.getElementById('yearly_revenue'));
const config = {
xAxis: {
type: 'category',
name: '/月',
data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
axisLabel: { show: true },
nameTextStyle: { padding: [0, 0, 0, -10] }
},
yAxis: {
name: '単位: 円',
nameTextStyle: { padding: [0, 24, -10, 0] }
},
series: [{
type: 'bar',
data: [5000, 2772, 3006, 2210, 1770, 2420, 4566, 2370, 3006, 2570, 1770, 2420],
itemStyle: {
color: params => params.value >= 0 ? '#E82724' : '#00A212'
}
}]
};
yearlyChart.setOption(config);