Google Apps Script: How to set “Use column A as labels” in chart embedded in spreadsheet?

谁都会走 提交于 2019-11-26 06:07:37

问题


I am using Google Apps Script and EmbeddedChartBuilder to embed line charts within my Google Spreadsheet. When you create these charts by hand, you have the (non-default) option to \"Use column A as labels\" (where \"A\" is the first column in the data range). I cannot find a way to do the same from a script. From the Google Visualization Line Chart documentation, it appears that the default is to treat the first column as having the \"domain\" role; but EmbeddedChartBuilder seems to override this and give all columns the \"data\" role. Since I don\'t have an explicit DataTable, I have no way to set the column roles myself.

Have I missed a way to do this? Or do I have to switch approaches from EmbeddedChartBuilder to using the spreadsheet as a data source?


回答1:


Found it! Set the option useFirstColumnAsDomain to true with EmbeddedChartBuilder.setOption.

This option appears to be undocumented. I found it by going to "Publish chart" (click on the chart, then select from the drop-down in the top right) and inspecting the JavaScript data structure in the given code. To be exact, I created a chart with "Use column A as labels" unchecked, grabbed the publish data structure, then checked "use column A as labels", grabbed the new publish data structure, and compared the two. To compare, I suggest normalizing the JSON and running diff. This technique can be used to reverse-engineer any settings in the chart editor.




回答2:


I just experienced this same problem. I took a similar approach as Andrew, but found a different solution (presumably because Google has added functionality to their graphs in Spreadsheets).

I used http://jsbeautifier.org/ to format the code after publishing, and I found this part to be responsible for adding the data labels. Note that you can even change the color of the stem that connects the bar to the data label:

"series": {
                    "0": {
                        "errorBars": {
                            "errorType": "none"
                        },
                        "dataLabel": "value",
                        "annotations": {
                            "stemColor": "none"
                        }
                    },
                    "color": "black",
                    "targetAxisIndex": 0,
                    "annotations": {
                        "textStyle": {
                            "color": "red",
                            "fontSize": 12
                        }
                    }
                },


来源:https://stackoverflow.com/questions/13594839/google-apps-script-how-to-set-use-column-a-as-labels-in-chart-embedded-in-spr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!