Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
27ac391
Style argument to timeseries plot
FrejaTerpPetersen Nov 5, 2024
c972683
first value is obs style
FrejaTerpPetersen Nov 5, 2024
3619190
Added color argument
FrejaTerpPetersen Nov 5, 2024
72d3210
Created function for checking inputs
FrejaTerpPetersen Nov 6, 2024
dfef139
Decided to only allow color OR style input
FrejaTerpPetersen Nov 6, 2024
a68fcfd
Wrote tests
FrejaTerpPetersen Nov 6, 2024
320563d
Deleted test call
FrejaTerpPetersen Nov 6, 2024
d55b4c7
docstring update
FrejaTerpPetersen Nov 6, 2024
d2d57e3
Design decision
FrejaTerpPetersen Nov 6, 2024
4446709
Removed unused import
FrejaTerpPetersen Nov 6, 2024
3a1fcba
Fix type error: color was not subscriptable if None
FrejaTerpPetersen Nov 6, 2024
0f57302
Wrong type error ... Moved default coloring
FrejaTerpPetersen Nov 6, 2024
1a70efb
Import default colors
FrejaTerpPetersen Nov 6, 2024
13a7163
Allow color to be tuple
FrejaTerpPetersen Nov 6, 2024
3f941aa
Moved import outside plot code
FrejaTerpPetersen Nov 6, 2024
f4d22ff
Merge remote-tracking branch 'origin/main' into timeseries-plot-style
jsmariegaard Nov 13, 2024
5cf2d03
Example notebook with timeseries plotting
jsmariegaard Nov 20, 2024
9337b8e
Specify only matplotlib backend in docstring
FrejaTerpPetersen Mar 12, 2025
fb44f8a
Moved check function from misc to top of comparer_plotter
FrejaTerpPetersen Mar 12, 2025
6b4476c
Rewrite check function
FrejaTerpPetersen Mar 12, 2025
5c0a029
remove unused code, update test
FrejaTerpPetersen Mar 12, 2025
9b69219
Not (yet) implemented in plotly
ecomodeller Mar 12, 2025
33f631a
Add plotly as test dependency
ecomodeller Mar 12, 2025
dc858ea
Merge branch 'main' into timeseries-plot-style
ecomodeller Mar 12, 2025
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
56 changes: 54 additions & 2 deletions modelskill/comparison/_comparer_plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@
from ..settings import options


def _check_arg_length_match_nmodels(arg, n_mod):
if isinstance(arg, str):
# If arg is str, convert to list (for looping)
arg = [arg]
if arg is not None and len(arg) < n_mod:
Copy link
Member

Choose a reason for hiding this comment

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

This doesn't account for the case where the user passes more arguments than n_mod. This should not be silently ignored.

raise ValueError(
f"Number of elements in {arg} does not match the number of models in the comparer."
)
return arg


class ComparerPlotter:
"""Plotter class for Comparer

Expand Down Expand Up @@ -62,6 +73,8 @@ def timeseries(
ax=None,
figsize: Tuple[float, float] | None = None,
backend: str = "matplotlib",
style: list[str] | str | None = None,
color: list[str] | tuple | str | None = None,
**kwargs,
):
"""Timeseries plot showing compared data: observation vs modelled
Expand All @@ -79,32 +92,62 @@ def timeseries(
backend : str, optional
use "plotly" (interactive) or "matplotlib" backend,
by default "matplotlib"
style: list of str, optional
Only for matplotlib backend. Containing line styles of the model results. Cannot be passed together with color input.
by default None
color: list of str, optional
Only for matplotlib backend. containing colors of the model results.
If len(colors) == num_models + 1, the first color will be used for the observations.
Cannot be passed together with style input.
by default None
**kwargs
other keyword arguments to fig.update_layout (plotly backend)

Returns
-------
matplotlib.axes.Axes or plotly.graph_objects.Figure
"""

from ._comparison import MOD_COLORS

cmp = self.comparer

if title is None:
title = cmp.name

if color is not None and style is not None:
raise ValueError(
"It is not possible to pass both the color argument and the style argument. Choose one."
)

# Color for observations:
obs_color = cmp.data[cmp._obs_name].attrs["color"]

color = _check_arg_length_match_nmodels(color, cmp.n_models)
style = _check_arg_length_match_nmodels(style, cmp.n_models)

if color is not None and len(color) > cmp.n_models:
# If more than n_models colors is given, the first color is used for the observations
obs_color = color[0]
color = color[1:]

if backend == "matplotlib":
fig, ax = _get_fig_ax(ax, figsize)
for j in range(cmp.n_models):
key = cmp.mod_names[j]
mod = cmp.raw_mod_data[key]._values_as_series
mod.plot(ax=ax, color=MOD_COLORS[j])
if style is not None:
mod.plot(ax=ax, style=style[j])
else:
if color is None:
color = MOD_COLORS
mod.plot(ax=ax, color=color[j])

ax.scatter(
cmp.time,
cmp.data[cmp._obs_name].values,
marker=".",
Copy link
Member

Choose a reason for hiding this comment

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

style does not affect the observations, is this the intended behaviour?

Copy link
Author

@FrejaTerpPetersen FrejaTerpPetersen Mar 12, 2025

Choose a reason for hiding this comment

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

Yes, observations can't have their style changed now. THis is a design choice, I guess? We could allow the user to input style for obs? Might lead to confusion, however, since I guess the user is pretty happy with a dot for the obs

Copy link
Member

Choose a reason for hiding this comment

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

I see the color can be changed. But not the marker.

color=cmp.data[cmp._obs_name].attrs["color"],
color=obs_color,
)
ax.set_ylabel(cmp._unit_text)
ax.legend([*cmp.mod_names, cmp._obs_name])
Expand All @@ -117,6 +160,15 @@ def timeseries(
elif backend == "plotly": # pragma: no cover
import plotly.graph_objects as go # type: ignore

if style is not None:
raise NotImplementedError(
"style argument is not supported for plotly backend"
)
if color is not None:
raise NotImplementedError(
"color argument not supported for plotly backend"
)

mod_scatter_list = []
for j in range(cmp.n_models):
key = cmp.mod_names[j]
Expand Down
137 changes: 137 additions & 0 deletions notebooks/Plotting_timeseries.ipynb

Large diffs are not rendered by default.

20 changes: 10 additions & 10 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,18 @@ docs = [
"dask",
]

dev = ["pytest", "plotly >= 4.5", "ruff==0.6.2"]

test = [
"pytest",
"pytest-cov",
"openpyxl",
"dask",
"mypy",
"types-PyYAML",
"geopandas",
test = [
"pytest",
"pytest-cov",
"netCDF4",
"openpyxl",
"dask",
"mypy",
"geopandas",
"plotly",
]


notebooks = ["nbformat", "nbconvert", "jupyter", "plotly", "shapely", "seaborn"]

[project.urls]
Expand Down
37 changes: 33 additions & 4 deletions tests/test_comparer.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import matplotlib.pyplot as plt
import numpy as np
import pytest
import pandas as pd
import pytest
import xarray as xr
import matplotlib.pyplot as plt
from modelskill.comparison import Comparer
from modelskill import __version__

import modelskill as ms
from modelskill import __version__
from modelskill.comparison import Comparer


@pytest.fixture
Expand Down Expand Up @@ -889,6 +890,34 @@ def test_from_matched_dfs0():
) == pytest.approx(0.0476569069177831)


def test_timeseriesplot_accepts_style_color_input(pc):
# Check that it can take the inputs
ax = pc.plot.timeseries(color=["red", "blue"])
ax = pc.plot.timeseries(style=["b-", "g--"])
assert ax.lines[1].get_color() == "g"

# Check that errors are raised
with pytest.raises(ValueError, match="Choose one"):
ax = pc.plot.timeseries(color=["red", "blue"], style="b-")
with pytest.raises(ValueError, match="number of models"):
ax = pc.plot.timeseries(color=["red"])
with pytest.raises(ValueError, match="number of models"):
ax = pc.plot.timeseries(style=["b-"])

ax = pc.plot.timeseries(color=["red", "blue", "black"])
# first line is blue (red is for observations).
assert ax.lines[0].get_color() == "blue"
plt.show()


def test_timeseriesplot_plotly_does_not_accept_style_color_input(pc):
with pytest.raises(NotImplementedError):
pc.plot.timeseries(backend="plotly", style=["b-", "g--"])

with pytest.raises(NotImplementedError):
pc.plot.timeseries(backend="plotly", color=["red", "blue"])


def test_from_matched_x_or_x_item_not_both():
with pytest.raises(ValueError, match="x and x_item cannot both be specified"):
ms.from_matched(
Expand Down