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

Fix/update libs #28

Merged
merged 14 commits into from
Dec 6, 2023
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
3 changes: 3 additions & 0 deletions .github/workflows/plotly_ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ jobs:
- name: Run formatter
run: make lint

- name: Run stubs install
run: make stubs

- name: Run checks
run: make checks

Expand Down
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ checks:
@poetry run pytest tests/
@poetry run poetry check

stubs:
@poetry run mypy --install-types --non-interactive plotly_calplot
@poetry run python3 -m pip install types-pytz

pypi_deploy:
@poetry config pypi-token.pypi $(PLOTLY_PRD_TOKEN)
@poetry build
Expand Down
Binary file removed dist/plotly_calplot-0.1.0-py3-none-any.whl
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.0.tar.gz
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.1-py3-none-any.whl
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.1.tar.gz
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.2-py3-none-any.whl
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.2.tar.gz
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.3-py3-none-any.whl
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.3.tar.gz
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.4-py3-none-any.whl
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.4.tar.gz
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.5-py3-none-any.whl
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.5.tar.gz
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.6-py3-none-any.whl
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.6.tar.gz
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.7-py3-none-any.whl
Binary file not shown.
Binary file removed dist/plotly_calplot-0.1.7.tar.gz
Binary file not shown.
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
2 changes: 1 addition & 1 deletion plotly_calplot/date_extractors.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def get_month_names(


def get_date_coordinates(
data: pd.DataFrame, x: str, start_month: int, end_month: int
data: pd.DataFrame, x: str
) -> Tuple[Any, List[float], List[int]]:
month_days = []
for m in data[x].dt.month.unique():
Expand Down
6 changes: 3 additions & 3 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 All @@ -40,7 +40,7 @@ def year_calplot(

month_names = get_month_names(data, x, start_month, end_month)
month_positions, weekdays_in_year, weeknumber_of_dates = get_date_coordinates(
data, x, start_month, end_month
data, x
)

# the calendar is actually a heatmap :)
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
)
Loading