Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support custom reference lines #36

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions lib/sparkline_svg.ex
Original file line number Diff line number Diff line change
Expand Up @@ -122,18 +122,26 @@ defmodule SparklineSvg do
reference lines as you want. Reference lines are displayed as horizontal lines that span the
entire width of the chart.

There are four types of currently supported reference lines:
There are currently four types of supported reference lines:
- `:max` - show the maximum value of the chart.
- `:min` - show the minimum value of the chart.
- `:avg` - show the average value of the chart.
- `:median` - show the median value of the chart.

You can implement custom reference lines by passing a function that receives `Core.points()`
and returns the `y` value at which to display the line. See examples in tests.

``` elixir
svg =
datapoints
|> SparklineSvg.new()
|> SparklineSvg.show_line()
|> SparklineSvg.show_ref_line(:max, color: "red")
|> SparklineSvg.show_ref_line(fn points ->
Enum.reduce(points, 0, fn {_x, y}, acc ->
y + acc
end) / 3
end, color: "blue")
|> SparklineSvg.to_svg!()
```

Expand Down Expand Up @@ -304,7 +312,7 @@ defmodule SparklineSvg do
| list({NaiveDateTime.t(), NaiveDateTime.t()})

@typedoc "The type of reference line."
@type ref_line :: :max | :min | :avg | :median
@type ref_line :: :max | :min | :avg | :median | (Core.points() -> Core.y())

@typedoc "Padding options for the chart."
@type padding ::
Expand Down
41 changes: 6 additions & 35 deletions lib/sparkline_svg/core.ex
Original file line number Diff line number Diff line change
Expand Up @@ -89,48 +89,19 @@ defmodule SparklineSvg.Core do
defp calc_resize_ref_lines(ref_lines, datapoints, min_max_y, options) do
ref_lines
|> Enum.map(fn {type, ref_line} ->
value = calc_ref_line(type, datapoints)
value =
cond do
is_atom(type) -> apply(ReferenceLine, type, [datapoints])
is_function(type, 1) -> type.(datapoints)
end

position = resize_y(value, min_max_y, options)

{type, %ReferenceLine{ref_line | position: position, value: value}}
end)
|> Map.new()
end

@spec calc_ref_line(SparklineSvg.ref_line(), points()) :: y()
defp calc_ref_line(:max, datapoints) do
{_x, y} = Enum.max_by(datapoints, fn {_x, y} -> y end)
y
end

defp calc_ref_line(:min, datapoints) do
{_x, y} = Enum.min_by(datapoints, fn {_x, y} -> y end)
y
end

defp calc_ref_line(:avg, datapoints) do
{sum, count} =
Enum.reduce(datapoints, {0, 0}, fn {_x, y}, {sum, count} -> {sum + y, count + 1} end)

sum / count
end

defp calc_ref_line(:median, datapoints) do
sorted_datapoints = Enum.sort_by(datapoints, fn {_x, y} -> y end)
length = Enum.count(sorted_datapoints)
mid = div(length, 2)

if rem(length, 2) == 0 do
{_x, left} = Enum.at(sorted_datapoints, mid - 1)
{_x, right} = Enum.at(sorted_datapoints, mid)

(left + right) / 2
else
{_x, y} = Enum.at(sorted_datapoints, mid)
y
end
end

@spec resize_x(number(), min_max(), SparklineSvg.opts()) :: number()
defp resize_x(x, {min_x, max_x}, %{width: width, padding: padding}) do
inner_width = width - padding.left - padding.right
Expand Down
64 changes: 63 additions & 1 deletion lib/sparkline_svg/reference_line.ex
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
defmodule SparklineSvg.ReferenceLine do
@moduledoc false

alias SparklineSvg.Core
alias SparklineSvg.ReferenceLine

@type ref_line_opts :: %{
Expand Down Expand Up @@ -39,8 +40,69 @@ defmodule SparklineSvg.ReferenceLine do

cond do
keys == [] -> {:ok, ref_lines}
Enum.all?(keys, &Enum.member?(@valid_types, &1)) -> {:ok, ref_lines}
Enum.all?(keys, &valid_type?/1) -> {:ok, ref_lines}
true -> {:error, :invalid_ref_line_type}
end
end

@spec max(Core.points()) :: Core.y()
def max(datapoints) do
{_x, y} = Enum.max_by(datapoints, fn {_x, y} -> y end)
y
end

@spec min(Core.points()) :: Core.y()
def min(datapoints) do
{_x, y} = Enum.min_by(datapoints, fn {_x, y} -> y end)
y
end

@spec avg(Core.points()) :: Core.y()
def avg(datapoints) do
{sum, count} =
Enum.reduce(datapoints, {0, 0}, fn {_x, y}, {sum, count} -> {sum + y, count + 1} end)

sum / count
end

@spec median(Core.points()) :: Core.y()
def median(datapoints) do
sorted_datapoints = Enum.sort_by(datapoints, fn {_x, y} -> y end)
length = Enum.count(sorted_datapoints)
mid = div(length, 2)

if rem(length, 2) == 0 do
{_x, left} = Enum.at(sorted_datapoints, mid - 1)
{_x, right} = Enum.at(sorted_datapoints, mid)

(left + right) / 2
else
{_x, y} = Enum.at(sorted_datapoints, mid)
y
end
end

@spec percentile(integer()) :: (Core.points() -> Core.y())
def percentile(nth) do
fn datapoints ->
values_count = length(datapoints)

case nth / 100 * (values_count + 1) do
n when n < 1 ->
0

n ->
sorted_values = Enum.map(datapoints, &elem(&1, 1)) |> Enum.sort()

case Enum.drop(sorted_values, max(0, trunc(n) - 1)) do
[a, b | _] -> a + (n - trunc(n)) * (b - a)
[a] -> a
end
end
end
end

defp valid_type?(type) when type in @valid_types, do: true
defp valid_type?(fun) when is_function(fun, 1), do: true
defp valid_type?(_), do: false
end
6 changes: 4 additions & 2 deletions mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ defmodule SparklineSvg.MixProject do
{"LICENSE", [title: "License"]}
],
authors: ["Gil Clavien"]
]
],
preferred_cli_env: ["test.watch": :test]
]
end

Expand All @@ -41,7 +42,8 @@ defmodule SparklineSvg.MixProject do
[
{:credo, "~> 1.7", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false},
{:ex_doc, "~> 0.31", only: :dev, runtime: false}
{:ex_doc, "~> 0.31", only: :dev, runtime: false},
{:mix_test_watch, "~> 1.0", only: :test, runtime: false}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great addition, thanks!

]
end

Expand Down
1 change: 1 addition & 0 deletions mix.lock
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@
"makeup": {:hex, :makeup, "1.1.1", "fa0bc768698053b2b3869fa8a62616501ff9d11a562f3ce39580d60860c3a55e", [:mix], [{:nimble_parsec, "~> 1.2.2 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "5dc62fbdd0de44de194898b6710692490be74baa02d9d108bc29f007783b0b48"},
"makeup_elixir": {:hex, :makeup_elixir, "0.16.1", "cc9e3ca312f1cfeccc572b37a09980287e243648108384b97ff2b76e505c3555", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "e127a341ad1b209bd80f7bd1620a15693a9908ed780c3b763bccf7d200c767c6"},
"makeup_erlang": {:hex, :makeup_erlang, "0.1.4", "29563475afa9b8a2add1b7a9c8fb68d06ca7737648f28398e04461f008b69521", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "f4ed47ecda66de70dd817698a703f8816daa91272e7e45812469498614ae8b29"},
"mix_test_watch": {:hex, :mix_test_watch, "1.2.0", "1f9acd9e1104f62f280e30fc2243ae5e6d8ddc2f7f4dc9bceb454b9a41c82b42", [:mix], [{:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}], "hexpm", "278dc955c20b3fb9a3168b5c2493c2e5cffad133548d307e0a50c7f2cfbf34f6"},
"nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"},
}
25 changes: 25 additions & 0 deletions test/sparkline_svg_ref_line_test.exs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
defmodule SparklineSvgMRefLineTest do
use ExUnit.Case, async: true

alias SparklineSvg.ReferenceLine

test "invalid ref line" do
assert SparklineSvg.new([1, 2]) |> SparklineSvg.show_ref_line(:foo) |> SparklineSvg.dry_run() ==
{:error, :invalid_ref_line_type}
Expand Down Expand Up @@ -85,4 +87,27 @@ defmodule SparklineSvgMRefLineTest do
assert sparkline.ref_lines.avg.value == 1.75
assert sparkline.ref_lines.median.value == 1.5
end

test "valid custom ref lines" do
fixed = fn _ -> 0.33 end
percentile_99 = ReferenceLine.percentile(99)

{:ok, sparkline} =
SparklineSvg.new(1..200)
|> SparklineSvg.show_ref_line(percentile_99)
|> SparklineSvg.show_ref_line(fixed)
|> SparklineSvg.dry_run()

assert sparkline.ref_lines[percentile_99].value == 198.99
assert sparkline.ref_lines[fixed].value == 0.33
end

test "custom ref line with empty chart" do
fun = fn _ -> 7 end

{:ok, sparkline} =
SparklineSvg.new([]) |> SparklineSvg.show_ref_line(fun) |> SparklineSvg.dry_run()

assert sparkline.ref_lines[fun].value == nil
end
end