There is an official example with custom lines that could be updated to your requirements. It has the advantage of showing/hiding connecting lines when the legend is selected/deselected.