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

Timeseries plot style #465

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
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
41 changes: 39 additions & 2 deletions modelskill/comparison/_comparer_plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
_xtick_directional,
_ytick_directional,
quantiles_xy,
_check_kwarg_and_convert_to_list,
)
from ..plotting import taylor_diagram, scatter, TaylorPoint
from ..settings import options
Expand Down Expand Up @@ -62,6 +63,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 +82,66 @@ def timeseries(
backend : str, optional
use "plotly" (interactive) or "matplotlib" backend,
by default "matplotlib"
style: list of str, optional
containing line styles of the model results. Cannot be passed together with color input.
by default None
color: list of str, optional
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"]

# if color is None and style is None: # Use default values for colors
Copy link
Member

Choose a reason for hiding this comment

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

remove unused code

# from ._comparison import MOD_COLORS

# color = MOD_COLORS[: cmp.n_models]

color, style = _check_kwarg_and_convert_to_list(color, 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])
Copy link
Member

Choose a reason for hiding this comment

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

I suggest to add a check (outside the loop) that the length of the style list is the same as the number of models (or models+1 obs, see comment below).

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?

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 Down
23 changes: 23 additions & 0 deletions modelskill/plotting/_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,26 @@ def _format_skill_line(
name = name.upper()

return f"{name}", " = ", f"{fvalue} {item_unit}"


def _check_kwarg_and_convert_to_list(color, style, n_mod):
if isinstance(style, str):
# If style is str, convert to list (for looping)
style = [style]
if isinstance(color, str):
# Same with color
color = [color]

if color is not None and len(color) < n_mod: # too few colors given?
raise ValueError(
"Number of colors in 'color' argument does not match the number of models in the comparer."
)

if (
style is not None and len(style) < n_mod and style[0] is not None
): # too few styles given?
raise ValueError(
"Number of styles in 'style' argument does not match the number of models in the comparer."
)

return color, style
137 changes: 137 additions & 0 deletions notebooks/Plotting_timeseries.ipynb

Large diffs are not rendered by default.

29 changes: 25 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,26 @@ 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="'color' argument"):
ax = pc.plot.timeseries(color=["red"])
with pytest.raises(ValueError, match="'style' argument"):
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_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
Loading