2
$\begingroup$

I can't seem to get Barchart to recognize TimeSeries data. For example, my data is:

{{1891, 1}, {1892, 1}, {1897, 1}, {1898, 1}, {1903, 1}, {1904, 1}, {1905, 1}, {1908, 4}, {1909, 6}, {1910, 6}, {1911, 16}, {1912, 33}, {1913, 35}, {1914, 43}, {1915, 39}, {1916, 31}, {1917, 42}, {1918, 52}, {1919, 44}, {1920, 53}, {1921, 33}, {1922, 18}, {1923, 8}}

But when I plot it using

BarChart[TimeSeries[data]]

I get this:

barchart

The problems are that it does not put the years values on the x-axis, and even worse it does treat the x-values as a linear time series. There should be gaps between 1892 and 1897, because there is no data for 1893, 1894, 1895 and 1896.

$\endgroup$
  • 1
    $\begingroup$ This is documented behavior for TimeSeries, EventSeries, and TemporalData. Also, BarChart is a categorical plot, so it doesn't understand about gaps. You'd have to insert them, yourself. I'd suggest using ListPlot[TimeSeries[data], Filling -> Axis], instead. $\endgroup$ – rcollyer Apr 23 '15 at 20:15
  • $\begingroup$ @rcollyer Hmm, that does create a stem plot which is of the right form, but if I want to make a BarChart there is no way except to create fake data with 0 values for the gaps and then add in the x-labels manually too? Seems kind of onerous. $\endgroup$ – Tyler Durden Apr 23 '15 at 20:28
  • $\begingroup$ Apparently, TimeSeries can be resampled without much drama, see Kirma's answer. $\endgroup$ – rcollyer Apr 23 '15 at 20:37
6
$\begingroup$
Module[{data, range},
 data = TimeSeries[#, ResamplingMethod -> {"Constant", 0}] &@{{1891, 
     1}, {1892, 1}, {1897, 1}, {1898, 1}, {1903, 1}, {1904, 1}, {1905,
      1}, {1908, 4}, {1909, 6}, {1910, 6}, {1911, 16}, {1912, 
     33}, {1913, 35}, {1914, 43}, {1915, 39}, {1916, 31}, {1917, 
     42}, {1918, 52}, {1919, 44}, {1920, 53}, {1921, 33}, {1922, 
     18}, {1923, 8}};
 range = Range[data["FirstTime"], data["LastTime"]];
 BarChart[data /@ range, 
  ChartLabels -> Placed[range, Below, Rotate[#, Pi/2.4] &], 
  ImageSize -> Large]]

enter image description here

$\endgroup$
  • $\begingroup$ Hey! That's cheating. :) (+1) $\endgroup$ – rcollyer Apr 23 '15 at 20:36
  • $\begingroup$ @rcollyer I'd like to have some other constant than 0 for missing data, but in that case chart labels for missing data seem to be also omitted. $\endgroup$ – kirma Apr 23 '15 at 20:38
  • 1
    $\begingroup$ I don't know, I don't mind the gaps when using Missing["NotAvailable"] as the constant. But, it works just fine as is. $\endgroup$ – rcollyer Apr 23 '15 at 20:41
  • $\begingroup$ Great answer !!! $\endgroup$ – eldo Apr 23 '15 at 20:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.