Skip to content

Commit

Permalink
add fixes and docs for datetimes
Browse files Browse the repository at this point in the history
  • Loading branch information
Bruno Rodrigues committed Dec 6, 2023
1 parent 8e8bb4e commit 111c4c9
Show file tree
Hide file tree
Showing 7 changed files with 184 additions and 80 deletions.
5 changes: 2 additions & 3 deletions examples/plotly_fig_show.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
dummy_end_date = "2022-10-03"
dummy_df = pd.DataFrame(
{
"ds": pd.date_range(dummy_start_date, dummy_end_date),
"ds": pd.date_range(dummy_start_date, dummy_end_date, tz="Singapore"),
"value": np.random.randint(
-10,
30,
Expand All @@ -17,6 +17,7 @@
),
}
)

fig1 = calplot(
dummy_df,
x="ds",
Expand All @@ -30,7 +31,5 @@
dummy_df,
x="ds",
y="value",
dark_theme=True,
showscale=True,
)
fig2.show()
25 changes: 21 additions & 4 deletions plotly_calplot/calplot.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import date
from typing import Any, Dict, Optional
from typing import Any, Dict, Optional, Union

import numpy as np
from pandas import DataFrame, Grouper, Series
Expand All @@ -11,7 +11,7 @@
showscale_of_heatmaps,
)
from plotly_calplot.single_year_calplot import year_calplot
from plotly_calplot.utils import fill_empty_with_zeros
from plotly_calplot.utils import fill_empty_with_zeros, validate_date_column


def _get_subplot_layout(**kwargs: Any) -> go.Layout:
Expand Down Expand Up @@ -65,7 +65,7 @@ def calplot(
colorscale: str = "greens",
title: str = "",
month_lines: bool = True,
total_height: int = None,
total_height: Union[int, None] = None,
space_between_plots: float = 0.08,
showscale: bool = False,
text: Optional[str] = None,
Expand All @@ -74,6 +74,7 @@ def calplot(
cmap_max: Optional[float] = None,
start_month: int = 1,
end_month: int = 12,
date_fmt: str = "%Y-%m-%d",
) -> go.Figure:
"""
Yearly Calendar Heatmap
Expand Down Expand Up @@ -149,7 +150,15 @@ def calplot(
end_month : int = 12
ending month range to plot, defaults to 12 (December)
date_fmt : str = "%Y-%m-%d"
date format for the date column in data, defaults to "%Y-%m-%d"
If the date column is already in datetime format, this parameter
will be ignored.
"""
print(data[x])
data[x] = validate_date_column(data[x], date_fmt)
print(data[x])
unique_years = data[x].dt.year.unique()
unique_years_amount = len(unique_years)
if years_title:
Expand Down Expand Up @@ -236,8 +245,9 @@ def month_calplot(
colorscale: str = "greens",
title: str = "",
year_height: int = 30,
total_height: int = None,
total_height: Union[int, None] = None,
showscale: bool = False,
date_fmt: str = "%Y-%m-%d",
) -> go.Figure:
"""
Yearly Calendar Heatmap by months (12 cols per row)
Expand Down Expand Up @@ -279,6 +289,11 @@ def month_calplot(
showscale : bool = False
wether to show the scale of the data
date_fmt : str = "%Y-%m-%d"
date format for the date column in data, defaults to "%Y-%m-%d"
If the date column is already in datetime format, this parameter
will be ignored.
"""
if data is None:
if not isinstance(x, Series):
Expand All @@ -292,6 +307,8 @@ def month_calplot(
x = x.name
y = y.name

data[x] = validate_date_column(data[x], date_fmt)

gData = data.set_index(x)[y].groupby(Grouper(freq="M")).sum()
unique_years = gData.index.year.unique()
unique_years_amount = len(unique_years)
Expand Down
4 changes: 2 additions & 2 deletions plotly_calplot/single_year_calplot.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List, Optional
from typing import List, Optional, Union

from pandas.core.frame import DataFrame
from plotly import graph_objects as go
Expand Down Expand Up @@ -27,7 +27,7 @@ def year_calplot(
colorscale: str = "greens",
title: str = "",
month_lines: bool = True,
total_height: int = None,
total_height: Union[int, None] = None,
text: Optional[List[str]] = None,
text_name: Optional[str] = None,
years_as_columns: bool = False,
Expand Down
45 changes: 45 additions & 0 deletions plotly_calplot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ def fill_empty_with_zeros(
start_month: int,
end_month: int,
) -> pd.DataFrame:
"""
Fills empty dates with zeros in the selected year data.
Args:
selected_year_data (DataFrame): The data for the selected year.
x (str): The column name for the date values.
year (int): The year for which the data is being filled.
start_month (int): The starting month of the year.
end_month (int): The ending month of the year.
Returns:
pd.DataFrame: The final DataFrame with empty dates filled with zeros.
"""
if end_month != 12:
last_date = datetime(year, end_month + 1, 1) + timedelta(days=-1)
else:
Expand All @@ -20,3 +33,35 @@ def fill_empty_with_zeros(
df = pd.DataFrame({x: pd.date_range(year_min_date, year_max_date)})
final_df = df.merge(selected_year_data, how="left")
return final_df


def validate_date_column(date_column: pd.Series, date_fmt: str) -> pd.Series:
"""
Validate the date column from a DataFrame.
Parameters:
data (DataFrame): The input DataFrame.
x (str): The name of the column containing the date values.
Returns:
pd.Series: The date column extracted from the DataFrame.
Raises:
ValueError: If the column is not in datetime format.
"""
if date_column.dtype == "datetime64[ns]":
return date_column
elif date_column.dtype == "object":
try:
return pd.to_datetime(date_column, format=date_fmt)
except ValueError:
raise ValueError(
f"Date column is not in the {date_fmt} format. Use change date_fmt parameter to match your dates." # noqa
)
try:
if date_column.dt.tz is not None:
return date_column.dt.tz_localize(None)
except Exception as e:
raise Exception(
f"Exception {e}\nDate column is not in datetime format or not in the right string format. Please convert it to datetime format first or use the date_fmt parameter." # noqa
)
111 changes: 43 additions & 68 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,17 @@ python = ">=3.8,<4.0.0"
plotly = "^5.4.0"
pandas = "*"
numpy = "^1.22.3"
pytz = "^2023.3.post1"

[tool.poetry.dev-dependencies]
[tool.poetry.group.dev.dependencies]
black = "^21.12b0"
isort = "^5.10.1"
streamlit = "^1.3.0"
pytest = "^7.1.1"
pytest-cov = "^3.0.0"
mypy = "^0.942"
flake8 = "^4.0.1"
vulture = "^2.3"
mypy = "^1.7.1"

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand Down
Loading

0 comments on commit 111c4c9

Please sign in to comment.