Hi,
the script is ok, it works as at the time of execution the dimensions which is RED in your editor is correct. The error is shown because of the fact that the validation is done statically and cannot know that you are exchanging the data source few lines above.
BTW, this what you want to achieve can be done also by having 2 data sources in the app and 2 charts, and then, on selection you can change the visibility of the chart. 2 DS means perhaps worse performance, but on frequent switches would be beneficial as the DS does not need to be reloaded.
you can try out what is better in your case.
Karol