[英]How to add legend to a react + d3 grouped and stacked bar chart?
I have a created a stacked and grouped bar chart with react + d3 and i want to add legend, i have added it like:我创建了一个带有 react + d3 的堆叠和分组条形图,我想添加图例,我已将其添加为:
{allKeys.map((key) => ( <div key={key} className="field" style={{ display: "flex" }}> <input id={key} type="checkbox" checked={keys.includes(key)} onChange={(e) => { if (e.target.checked) { setKeys(Array.from(new Set([...keys, key]))); } else { setKeys(keys.filter((_key) => _key !== key)); } }} /> <label htmlFor={key} style={{ color: colors[key] }}> {key} </label> </div> ))}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
but the problem is that when you toggle (for example clicking on facebook to toggle) it will change stack order (for example facebook color is green and it should be always at the bottom, but when you click on facebook legend to make it disappear and click again to appear first it is at the bottom and when you hide and show back it will go to the top)但问题是当你切换时(例如点击 facebook 切换)它会改变堆栈顺序(例如 facebook 颜色是绿色的,它应该总是在底部,但是当你点击 facebook 图例时,它会消失和再次单击以首先出现它在底部,当您隐藏并显示时它会转到顶部)
you can check the full code and demo in demo您可以在演示中查看完整代码和演示
any help to make it work will be appreciated任何帮助使它工作将不胜感激
Two possible solutions:两种可能的解决方案:
const initialItems = {
facebook: true,
google: true,
linkedin: true
}
{Object.keys(items).map((key) => (
<div key={key} className="field" style={{ display: "flex" }}>
<input
id={key}
type="checkbox"
checked={items[key]}
onChange={(e) => {
if (e.target.checked) {
items[key] = true;
} else {
items[key] = false;
}
setItems(items);
}}
/>
<label htmlFor={key} style={{ color: colors[key] }}>
{key}
</label>
</div>
))}
set
function to use allKeys
as a base:set
函数以使用allKeys
作为基础:if (e.target.checked) {
setKeys(allKeys.filter(k => keys.includes(k) || k === key));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.