The issue has been closed
<!--
Thank you for your pull request. Please review below requirements.
Bug fixes and new features should include tests and possibly benchmarks.
Contributors guide: https://github.com/antvis/g2/blob/master/CONTRIBUTING.md
感谢您贡献代码。请确认下列 checklist 的完成情况。
Bug 修复和新功能必须包含测试,必要时请附上性能测试。
Contributors guide: https://github.com/antvis/g2/blob/master/CONTRIBUTING.md
-->
If I have a chart like this:

I can show/hide fields by clicking the relevent items in the legend to get this:

Is there a way I can do that programatically via the API rather than getting the user to click?
I have tried to look through the documentation but I can't find a way to do it
Checklist
<!-- Remove items that do not apply. For completed items, change [ ] to [x]. -->
Description of change
<!-- Provide a description of the change below this comment. -->

What version of G2 are you using? V4 or V5?
posted by pearmini about 2 years ago
Hi @pearmini thanks for the reply. I am using @antv/g2plot: "^2.4.20"
which I think is using G2 version 4.
I can see in the legend section of the docs there is a selected
setting which you can use during initalisation to be able to show and hide the legend items, but I need to be able to do this dynamically at runtime
- I need to find an API to be able to get this information, for example from my picture above I need to be able to see that we are showing Exam 1, Exam2, and Exam 6; Exam 3, Exam 4, and Exam 5 are hidden
- I need to find an API to be able to set this dynamically during runtime too
posted by matteematt about 2 years ago
If you are using G2Plot, you can see this example for more details.
posted by pearmini about 2 years ago
I didn't really have any luck with setState
and getState
. I instead diffed the displayed data which you can get in the legend click callback which all of the data, so you can checks which legend items are selected
or not, and then you can recreate the chart and pass these values in via config.legend.selected
.
This does work but not an ideal solution
posted by matteematt about 2 years ago