Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dates in X-axis with Google chart API?

Is there a way to plot a chart with Google chart API so that the X-axis values are days in a month?

I have data points that are not provided with the same frequency. For example:

Date - Value 1/1/2009 - 100 1/5/2009 - 150 1/6/2009 - 165 1/13/2009 - 200 1/20/2009 - 350 1/30/2009 - 500 

I want to make a chart that will separate each data point with the relative distance based on time during a month. This can be done with Excel, but how can I calculate and display it with Google chart?

Other free solutions similar to Google chart or a free library that can be used with ASP.NET are also welcome.

like image 231
jvanderh Avatar asked Jun 19 '09 21:06

jvanderh


People also ask

How do I add dates to Google Sheets chart?

Select the Google Sheet you'd like to use for this widget (the "Spreadsheet" option) Select the tab that contains the data you want to use ("Spreadsheet Tab") Specify the date column in the "Dimension Column" in your pie chart or bar chart widget or in the "Date Column" in your table, line chart or sparkline widget.


1 Answers

UPDATE This is now supported directly in the Chart API using the advanced graphs "annotated chart" feature - https://developers.google.com/chart/interactive/docs/gallery/annotationchart

I have done this on my ReHash Database Statistics chart (even though the dates turned out to be evenly spaced, so it doesn't exactly demonstrate that it's doing this).

First, you want to get your overall time period, which will be analogous to the overall width of your chart. To do this we subtract the earliest date from the latest. I prefer to use Unix-epoch timestamps as they are integers and easy to compare in this way, but you could easily calculate the number of seconds, etc.

Now, loop through your data. For each date we want the percentile in the overall period that the date is from the beginning (i.e. the earliest date is 0, the latest is 100). For each date, you first want to calculate the distance of the present date from the earliest date in the data set. Essentially, "how far are we from the start". So, subtract the earliest date from the present date. Then, to find the percentile, we divide the distance of the present date by the overall time period, and then multiply by 100 and truncate or round any decimal to give our integral x-coordinate.

And it is as simple as that! Your x-values will range from 0 (the left-side of the chart) to 100 (the right side) and each data point will lie at a distance from the start respective of its true temporal distance.

If you have any questions, feel free to ask! I can post pesudocode or PHP if desired.

like image 100
defines Avatar answered Sep 23 '22 10:09

defines