Rails chartkick: want only integer values on axes. Use discrete or something else?

久未见 提交于 2019-12-04 11:54:09

问题


Say I have the following code

<% data = [
[1,1],[2,3],[3,5],[4,8],[6,4],[7,2]
] %>

<%= line_chart data,  {discrete: true, library: {width: 600} }%>

Using chartkick, this produces the following graph

I want the vertical axis to be labeled using integers. (not decimals) I thought that the discrete option was supposed to do this but for this example all it did was change the format of the elements on the horizontal axis from time to number (i.e. the following code

<%= line_chart data,  {library: {width: 600} }%>

produces this

).

So my question is: what exactly does discrete do, other than change dates that were actually numbers to numbers. How can I use it to make the numbers on the vertical axis integers? (Or, if it can't be used to do this, what can I use?)


回答1:


The discrete option applies only to the 'major axis' and is for a discrete axis. There's a difference between discrete and continuous axises that you should read up on.

And I just read the configuration options. Apparently you can pass a ticks option to each axis. And the ticks are markers. You could get the minimum and maximum value for each range from your data and then spread it out with a 1 integer interval.

Thus the following should work for you:

data = [[1,1],[2,3],[3,5],[4,8],[6,4],[7,2]]

x_values = data.map(&:first)
x_range = (x_values.min)..(x_values.max)

y_values = data.map(&:last)
y_range = (y_values.min)..(y_values.max)

library_options = {
  width: 600,
  hAxis: {ticks: x_range.to_a},
  vAxis: {ticks: y_range.to_a}
  # to_a because I don't know if Range is acceptable input
}

line_chart(data, {library: library_options})

For more options, take a look at Google Chart's configuration options for line charts.




回答2:


Just try this.: library: { yAxis: {allowDecimals: false } }

Source.: https://github.com/ankane/chartkick/issues/269



来源:https://stackoverflow.com/questions/27590771/rails-chartkick-want-only-integer-values-on-axes-use-discrete-or-something-els

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