Skip to content

Commit

Permalink
[Plot] Enhancements + Bug Fixes (#1301)
Browse files Browse the repository at this point in the history
* [Plot] Enhancements + Bug Fixes

 - multiple corrections
 - it is now possible to draw plots without agg

Should close:
 -

* correction

* Correcting the bug

* Bug correction

* correcting plotly pie
  • Loading branch information
oualib authored Oct 4, 2024
1 parent ea63f93 commit d70b7b2
Show file tree
Hide file tree
Showing 17 changed files with 203 additions and 74 deletions.
6 changes: 3 additions & 3 deletions verticapy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@
__url__: str = "https://github.com/vertica/verticapy/"
__license__: str = "Apache License, Version 2.0"
__version__: str = "1.1.0-beta"
__iteration__: int = 2
__date__: str = "10032024"
__last_commit__: str = "c4fa73aaaf54051fb35b325a5dd77573ba9b3f4c"
__iteration__: int = 1
__date__: str = "10042024"
__last_commit__: str = "b229f82d26eb61ddfc0375a7169e27a33f60340a"
__long_version__: str = f"{__version__}-{__iteration__}{__date__}-{__last_commit__}"
__codecov__: float = 0.84

Expand Down
4 changes: 3 additions & 1 deletion verticapy/_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,7 @@
PlottingObject = Union[
"PlottingBase", "TableSample", "Axes", "mFigure", "Highchart", "Highstock", "Figure"
]
PlottingMethod = Union[Literal["density", "count", "avg", "min", "max", "sum"], str]
PlottingMethod = Union[
Literal[None, "density", "count", "avg", "min", "max", "sum"], str
]
ColorType = str
3 changes: 2 additions & 1 deletion verticapy/core/vdataframe/_fill.py
Original file line number Diff line number Diff line change
Expand Up @@ -868,7 +868,8 @@ def fillna(
| ``vDataFrame.``:py:meth:`~verticapy.vDataFrame.interpolate` : Fill missing values by interpolating.
| ``vDataColumn.``:py:meth:`~verticapy.vDataColumn.fill_outliers` : Fill the outliers using the input method.
"""
method = method.lower()
if isinstance(method, str):
method = method.lower()
by, order_by = format_type(by, order_by, dtype=list)
by, order_by = self._parent.format_colnames(by, order_by)
if method == "auto":
Expand Down
58 changes: 49 additions & 9 deletions verticapy/core/vdataframe/_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,10 @@ def bar(
q Quantile of the
:py:class:`~vDataColumns` ``of``
(ex: 50% to get the median).
- None:
No Aggregations. Parameter ``of``
must not be empty, otherwise it
is ignored.
It can also be a cutomized aggregation,
for example: ``AVG(column1) + 5``
Expand Down Expand Up @@ -425,6 +429,14 @@ def bar(
categoryorder=categoryorder,
**style_kwargs,
)
elif len(columns) == 2 and isinstance(method, NoneType) and not (of):
return self[columns[0]].bar(
method=None,
of=columns[1],
max_cardinality=max_cardinality[0],
categoryorder=categoryorder,
**style_kwargs,
)
elif kind == "drilldown":
vpy_plt, kwargs = self.get_plotting_lib(
class_name="DrillDownBarChart",
Expand Down Expand Up @@ -529,6 +541,10 @@ def barh(
q Quantile of the
:py:class:`~vDataColumns` ``of``
(ex: 50% to get the median).
- None:
No Aggregations. Parameter ``of``
must not be empty, otherwise it
is ignored.
It can also be a cutomized aggregation,
for example: ``AVG(column1) + 5``
Expand Down Expand Up @@ -706,6 +722,14 @@ def barh(
categoryorder=categoryorder,
**style_kwargs,
)
elif len(columns) == 2 and isinstance(method, NoneType) and not (of):
return self[columns[0]].barh(
method=None,
of=columns[1],
max_cardinality=max_cardinality[0],
categoryorder=categoryorder,
**style_kwargs,
)
elif kind == "drilldown":
vpy_plt, kwargs = self.get_plotting_lib(
class_name="DrillDownHorizontalBarChart",
Expand Down Expand Up @@ -2163,6 +2187,11 @@ def hexbin(
q Quantile of the
:py:class:`~vDataColumns` ``of``
(ex: 50% to get the median).
- None:
No Aggregations. Parameter ``of``
must not be empty, otherwise it
is ignored. The function to draw
the final chart will be ``max```.
of: str, optional
The vDataColumn used to compute the aggregation.
Expand Down Expand Up @@ -2221,7 +2250,7 @@ def hexbin(
}
)
Below is an examples of one type of hexbin plots:
Below is an example of one type of hexbin plots:
- Hexbin
Expand Down Expand Up @@ -2805,9 +2834,9 @@ def numh(
fd = max(
2.0 * (vDataColumn_075 - vDataColumn_025) / (count) ** (1.0 / 3.0), 1e-99
)
if method.lower() == "sturges":
if str(method).lower() == "sturges":
best_h = sturges
elif method.lower() in ("freedman_diaconis", "fd"):
elif str(method).lower() in ("freedman_diaconis", "fd"):
best_h = fd
else:
best_h = max(sturges, fd)
Expand Down Expand Up @@ -3001,6 +3030,8 @@ def bar(
q Quantile of the
:py:class:`~vDataColumns` ``of``
(ex: 50% to get the median).
- None:
No Aggregations.
It can also be a cutomized aggregation
(ex: AVG(column1) + 5).
Expand Down Expand Up @@ -3122,7 +3153,7 @@ def bar(
@save_verticapy_logs
def barh(
self,
method: str = "density",
method: PlottingMethod = "density",
of: Optional[str] = None,
max_cardinality: int = 6,
nbins: int = 0,
Expand Down Expand Up @@ -3168,6 +3199,8 @@ def barh(
q Quantile of the
:py:class:`~vDataColumns` ``of``
(ex: 50% to get the median).
- None:
No Aggregations.
It can also be a cutomized aggregation
(ex: AVG(column1) + 5).
Expand Down Expand Up @@ -3289,7 +3322,7 @@ def barh(
@save_verticapy_logs
def pie(
self,
method: str = "density",
method: PlottingMethod = "density",
of: Optional[str] = None,
max_cardinality: int = 6,
h: PythonNumber = 0,
Expand Down Expand Up @@ -3333,6 +3366,8 @@ def pie(
q Quantile of the
:py:class:`~vDataColumns` ``of``
(ex: 50% to get the median).
- None:
No Aggregations.
It can also be a cutomized aggregation
(ex: ``AVG(column1) + 5``).
Expand Down Expand Up @@ -3452,7 +3487,7 @@ def pie(
def spider(
self,
by: Optional[str] = None,
method: str = "density",
method: PlottingMethod = "density",
of: Optional[str] = None,
max_cardinality: tuple[int, int] = (6, 6),
h: tuple[PythonNumber, PythonNumber] = (None, None),
Expand Down Expand Up @@ -3592,7 +3627,7 @@ def spider(
def hist(
self,
by: Optional[str] = None,
method: str = "density",
method: PlottingMethod = "density",
of: Optional[str] = None,
h: Optional[PythonNumber] = None,
h_by: PythonNumber = 0,
Expand Down Expand Up @@ -3935,7 +3970,7 @@ def density(
def candlestick(
self,
ts: str,
method: str = "sum",
method: PlottingMethod = "sum",
q: tuple[float, float] = (0.25, 0.75),
start_date: Optional[PythonScalar] = None,
end_date: Optional[PythonScalar] = None,
Expand Down Expand Up @@ -4020,6 +4055,12 @@ def candlestick(
import numpy as np
We can create a variable ``N`` to fix the size:
.. ipython:: python
N = 30
Let's generate a dataset using the following data.
.. ipython:: python
Expand All @@ -4037,7 +4078,6 @@ def candlestick(
data["population"].candlestick(ts = "date")
.. ipython:: python
:suppress:
:okwarning:
Expand Down
37 changes: 25 additions & 12 deletions verticapy/core/vdataframe/_sys.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def _get_catalog_value(
return "VERTICAPY_NOT_PRECOMPUTED"
return total
elif method:
method = verticapy_agg_name(method.lower())
method = verticapy_agg_name(str(method).lower())
if columns[1] in self[columns[0]]._catalog[method]:
return self[columns[0]]._catalog[method][columns[1]]
else:
Expand Down Expand Up @@ -1317,27 +1317,39 @@ def store_usage(self) -> int:
)
return store_usage

def rename(self, new_name: str) -> "vDataFrame":
def rename(
self,
new_name: str,
inplace: bool = True,
) -> "vDataFrame":
"""
Renames the vDataColumn by dropping the current vDataColumn
and creating a copy with the specified name.
Renames the vDataColumn. This function is not
directly applied to the input object.
.. warning::
SQL code generation will be slower if the
vDataFrame has been transformed multiple
times, so it's better practice to use this
method when first preparing your data.
It is even recommended to use directly
``vDataFrame.``:py:meth:`~verticapy.vDataFrame.select`
method and do all the renaming within
one single operation.
Parameters
----------
new_name: str
The new vDataColumn alias.
inplace: bool, optional
If set to ``True``, the
:py:class:`~vDataFrame` is replaced
with the new relation.
Returns
-------
vDataFrame
self._parent
result.
Examples
--------
Expand Down Expand Up @@ -1385,8 +1397,7 @@ def rename(self, new_name: str) -> "vDataFrame":
.. ipython:: python
:suppress:
vdf["val"].rename("value")
result = vdf
result = vdf["val"].rename("value", inplace=False)
html_file = open("SPHINX_DIRECTORY/figures/core_vDataFrame_sys_rename.html", "w")
html_file.write(result._repr_html_())
html_file.close()
Expand All @@ -1407,9 +1418,11 @@ def rename(self, new_name: str) -> "vDataFrame":
"By changing the parameter 'new_name', you'll "
"be able to solve this issue."
)
self._parent.eval(name=new_name, expr=old_name)
parent = self.drop(add_history=False)
parent._add_to_history(
f"[Rename]: The vDataColumn {old_name} was renamed '{new_name}'."
res = self._parent.select(
self._parent.get_columns(exclude_columns=[old_name])
+ [f"{old_name} AS {new_name}"]
)
return parent
if inplace:
self._parent.__init__(res.current_relation())
return self._parent
return res
4 changes: 2 additions & 2 deletions verticapy/plotting/_matplotlib/bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def draw(
xticks_label = xticks
ax.set_xticks(xticks)
ax.set_xticklabels(xticks_label, rotation=90)
ax.set_ylabel(self.layout["method"])
ax.set_ylabel(self.layout["method_of"])
return ax


Expand Down Expand Up @@ -151,7 +151,7 @@ def draw(
ax.set_xticks(xticks)
ax.set_xticklabels(self.layout["x_labels"], rotation=90)
ax.set_xlabel(self.layout["columns"][0])
ax.set_ylabel(self.layout["method"])
ax.set_ylabel(self.layout["method_of"])
ax.legend(
title=self.layout["columns"][1], loc="center left", bbox_to_anchor=[1, 0.5]
)
Expand Down
4 changes: 2 additions & 2 deletions verticapy/plotting/_matplotlib/barh.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def draw(
ax.set_yticks(
[x - round(self.data["width"] / 2, 10) for x in self.data["x"]]
)
ax.set_xlabel(self.layout["method"])
ax.set_xlabel(self.layout["method_of"])
return ax


Expand Down Expand Up @@ -187,7 +187,7 @@ def draw(
ax.set_yticks(yticks)
ax.set_yticklabels(self.layout["x_labels"])
ax.set_ylabel(self.layout["columns"][0])
ax.set_xlabel(self.layout["method"])
ax.set_xlabel(self.layout["method_of"])
if self.layout["kind"] in ("density", "fully_stacked"):
vals = ax.get_xticks()
max_val = max(abs(x) for x in vals)
Expand Down
6 changes: 3 additions & 3 deletions verticapy/plotting/_matplotlib/pie.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,11 @@ def draw(
):
current_explode = min(0.9, current_explode * 1.4)
explode[idx] = current_explode
if self.layout["method"].lower() == "density":
if str(self.layout["method"]).lower() == "density":
autopct = "%1.1f%%"
else:
if (self.layout["method"].lower() in ["sum", "count"]) or (
(self.layout["method"].lower() in ["min", "max"])
if (str(self.layout["method"]).lower() in ["sum", "count"]) or (
(str(self.layout["method"]).lower() in ["min", "max"])
and (self.layout["of_cat"] == "int")
):
category = "int"
Expand Down
2 changes: 1 addition & 1 deletion verticapy/plotting/_matplotlib/spider.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def draw(
ax.set_yticks(y_ticks)
ax.set_rgrids(y_ticks, angle=180.0, fmt="%0.1f")
ax.set_xlabel(self.layout["columns"][0])
ax.set_ylabel(self.layout["method"])
ax.set_ylabel(self.layout["method_of"])
if len(self.layout["columns"]) > 1:
ax.legend(
title=self.layout["columns"][1],
Expand Down
4 changes: 2 additions & 2 deletions verticapy/plotting/_plotly/bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def _compute_method(self) -> Literal["1D"]:
def _init_style(self) -> None:
self.init_trace_style = {"marker_color": self.get_colors(idx=0)}
self.init_layout_style = {
"yaxis_title": self.layout["method"],
"yaxis_title": self.layout["method_of"],
"xaxis_title": self.layout["column"],
"width": 100 + 100 * len(self.layout["labels"]),
"height": 500,
Expand Down Expand Up @@ -90,7 +90,7 @@ def _compute_method(self) -> Literal["2D"]:
# Styling Methods.
def _init_style(self) -> None:
self.init_layout_style = {
"yaxis_title": self.layout["method"],
"yaxis_title": self.layout["method_of"],
"legend_title_text": self.layout["columns"][1],
"xaxis_title": self.layout["columns"][0],
"width": (150 + 40 * len(self.layout["x_labels"]))
Expand Down
4 changes: 2 additions & 2 deletions verticapy/plotting/_plotly/barh.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def _compute_method(self) -> Literal["1D"]:
def _init_style(self) -> None:
self.init_trace_style = {"marker_color": self.get_colors(idx=0)}
self.init_layout_style = {
"xaxis_title": self.layout["method"],
"xaxis_title": self.layout["method_of"],
"yaxis_title": self.layout["column"],
# "width": 500 ,
"height": 100 * len(self.layout["labels"]),
Expand Down Expand Up @@ -89,7 +89,7 @@ def _compute_method(self) -> Literal["2D"]:

def _init_style(self) -> None:
self.init_layout_style = {
"xaxis_title": self.layout["method"],
"xaxis_title": self.layout["method_of"],
"legend_title_text": self.layout["columns"][1],
"yaxis_title": self.layout["columns"][0],
"width": 500,
Expand Down
3 changes: 2 additions & 1 deletion verticapy/plotting/_plotly/pie.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,10 @@ def _init_style(self) -> None:
"hovertemplate": "%{label} <extra></extra>",
}
self.init_layout_style = {
"title_text": self.layout["column"],
"title_text": self.layout["method_of"],
"title_x": 0.5,
"title_xanchor": "center",
"legend": {"title": self.layout["column"]},
}

# Draw
Expand Down
Loading

0 comments on commit d70b7b2

Please sign in to comment.