Skip to content
Merged
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
18 changes: 17 additions & 1 deletion lib/matplotex.ex
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,23 @@ defmodule Matplotex do
Spline.create(figure, {x, y}, opts)
end

@doc """
Creates a step plot with the given parameters
## Parameters

- `x` (list): A list of x-coordinates for the data points.
- `y` (list): A list of y-coordinates corresponding to the x-coordinates.
```elixir
x = [1,2,3,4,5]
y = [1,4,9,16,25]
Matplotex.step(x, y, color: "blue")
|>Matplotex.set_xlabel("Numbers")
|>Matplotex.set_ylabel("Squares")
```
"""
def step(x, y, opts), do: Matplotex.Figure.Areal.Step.create(x, y, opts)
def step(figure, x, y, opts), do: Matplotex.Figure.Areal.Step.create(figure, x, y, opts)

@doc """
Sets X labels for the graph with given font details

Expand All @@ -597,7 +614,6 @@ defmodule Matplotex do
%Matplotex.Figure{}

"""

@spec set_xlabel(Figure.t(), String.t()) :: Figure.t()
def set_xlabel(figure, label, opts \\ []) do
Figure.add_label(figure, {:x, label}, opts)
Expand Down
37 changes: 37 additions & 0 deletions lib/matplotex/figure/areal/step.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
defmodule Matplotex.Figure.Areal.Step do

alias Matplotex.Figure.Areal.LinePlot
alias Matplotex.Figure
alias Matplotex.InputError

def create(x, y, opts) do
{x, y} = step_segments(x, y)
LinePlot.create(%Figure{axes: %LinePlot{}}, {x, y}, opts)
end
def create(%Figure{} = figure, x, y, opts) do
{x, y} = step_segments(x, y)
LinePlot.create(figure, {x, y}, opts)
end
defp step_segments(x, y) do
x = horizontal_segments(x)
y = vertical_segments(y)
{x,y}
end
defp horizontal_segments(data) when is_list(data) do
first_value = List.first(data)
second_last_index = length(data) - 1
repeated = data|>Enum.slice(1..second_last_index)|>List.duplicate(2)|> List.flatten()
[first_value | repeated]|>Enum.sort()
end
defp horizontal_segments(_data), do: list_error(:y)

defp vertical_segments(data) when is_list(data) do
data|>List.duplicate(2)|>List.flatten()|>Enum.sort()
end
defp vertical_segments(_data), do: list_error(:y)

defp list_error(arg) do
raise InputError, message: "Expected a list for arg: #{arg}"
end

end
13 changes: 13 additions & 0 deletions test/matplotex_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -304,4 +304,17 @@ defmodule MatplotexTest do
assert data1.y == y
end
end

describe "step" do
test "creates a figure for step plot" do
x = [1, 2, 3, 4, 5]
y = [1,4,9,16,25]
assert %Figure{axes: %{dataset: [data1], label: label}} =
Matplotex.step(x, y, x_label: "X", y_label: "Y")
assert label.x == "X"
assert label.y == "Y"
assert data1.x|>Enum.uniq() == x
assert data1.y|>Enum.uniq() == y
end
end
end