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 for categorical plot with a single point #68

Merged
merged 1 commit into from
Oct 7, 2024
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
13 changes: 13 additions & 0 deletions tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,19 @@ def test_cat_plots(backend: str, orient: str):
cat_plt.add_heatmap_hist(bins=4, color="c").copy()
read_canvas(canvas.write_json())

def test_single_point():
import warnings

warnings.filterwarnings("error") # to make sure std is not called with single point
canvas = new_canvas(backend="mock")
df = {"cat": ["a", "b", "b", "c", "c", "c"], "val": np.arange(6)}
cat_plt = canvas.cat_x(df, "cat", "val")
cat_plt.add_barplot()
cat_plt.add_boxplot()
cat_plt.add_heatmap_hist()
cat_plt.add_pointplot()
cat_plt.add_violinplot()

def test_cat_plots_with_sequential_color():
df = {
"y": np.arange(30),
Expand Down
1 change: 1 addition & 0 deletions whitecanvas/backend/matplotlib/canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,7 @@
if _is_inline():
from IPython.display import display

self._fig.tight_layout()

Check warning on line 420 in whitecanvas/backend/matplotlib/canvas.py

View check run for this annotation

Codecov / codecov/patch

whitecanvas/backend/matplotlib/canvas.py#L420

Added line #L420 was not covered by tests
plt.close(self._fig)
display(self._fig)
else:
Expand Down
18 changes: 12 additions & 6 deletions whitecanvas/layers/group/band_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,18 @@
xyy_values: list[XYYData] = []
for offset, values in zip(x, data):
arr = as_array_1d(values)
kde = gaussian_kde(arr, bw_method=kde_band_width)

sigma = np.sqrt(kde.covariance[0, 0])
pad = sigma * 2.5
x_ = np.linspace(arr.min() - pad, arr.max() + pad, 100)
y = kde(x_)
if arr.size > 1:
kde = gaussian_kde(arr, bw_method=kde_band_width)
sigma = np.sqrt(kde.covariance[0, 0])
pad = sigma * 2.5
x_ = np.linspace(arr.min() - pad, arr.max() + pad, 100)
y = kde(x_)
elif arr.size == 1:
x_ = np.array([arr[0]])
y = np.array([1.0])
else:
x_ = np.array([])
y = np.array([])

Check warning on line 213 in whitecanvas/layers/group/band_collection.py

View check run for this annotation

Codecov / codecov/patch

whitecanvas/layers/group/band_collection.py#L212-L213

Added lines #L212 - L213 were not covered by tests
if shape in ("both", "left"):
y0 = -y + offset
else:
Expand Down
3 changes: 0 additions & 3 deletions whitecanvas/layers/group/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,9 @@
LineStyle,
Orientation,
OrientationLike,
_Void,
)
from whitecanvas.utils.normalize import as_any_1d_array, as_color_array

_void = _Void()


class BoxPlot(LayerContainer, AbstractFaceEdgeMixin["BoxFace", "BoxEdge"]):
"""
Expand Down
10 changes: 7 additions & 3 deletions whitecanvas/layers/group/labeled.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,16 +301,20 @@ def _as_legend_item(self) -> _legend.MarkerErrorLegendItem:
return _legend.MarkerErrorLegendItem(markers, xerr, yerr)


def _init_mean_sd(x, data, color):
def _init_mean_sd(x, data: list[ArrayLike1D], color):
x, data = check_array_input(x, data)
color = as_color_array(color, len(x))

est_data = []
err_data = []

for sub_data in data:
for each in data:
sub_data = np.asarray(each)
_mean = np.mean(sub_data)
_sd = np.std(sub_data, ddof=1)
if sub_data.size == 1:
_sd = 0
else:
_sd = np.std(sub_data, ddof=1)
est_data.append(_mean)
err_data.append(_sd)

Expand Down
16 changes: 9 additions & 7 deletions whitecanvas/layers/tabular/_box_like.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,6 @@

@classmethod
def from_dict(cls, d: dict[str, Any], backend: Backend | str | None = None) -> Self:
"""Create a DFViolinPlot from a dictionary."""
from whitecanvas.canvas.dataframe._base import CatIterator

base = d["base"]
Expand Down Expand Up @@ -793,8 +792,7 @@
high = q3 + ratio * iqr # upper bound of inliers
is_inlier = (low <= arr) & (arr <= high)
inliers = arr[is_inlier]
agg_values[0, idx_cat] = inliers.min()
agg_values[4, idx_cat] = inliers.max()
agg_values[:, idx_cat] = np.quantile(inliers, [0, 0.25, 0.5, 0.75, 1.0])
outliers = arr[~is_inlier]
for _cat, _s in zip(sl, self._splitby):
df_outliers[_s].extend([_cat] * outliers.size)
Expand Down Expand Up @@ -847,24 +845,26 @@
def est_by_mean(self) -> Self:
"""Set estimator to mean."""

def est_func(x):
def est_func(x: np.ndarray):
return np.mean(x)

return self._update_estimate(est_func)

def est_by_median(self) -> Self:
"""Set estimator to median."""

def est_func(x):
def est_func(x: np.ndarray):
return np.median(x)

return self._update_estimate(est_func)

def err_by_sd(self, scale: float = 1.0, *, ddof: int = 1) -> Self:
"""Set error to standard deviation."""

def err_func(x):
def err_func(x: np.ndarray):
_mean = np.mean(x)
if x.size <= ddof:
return _mean, _mean

Check warning on line 867 in whitecanvas/layers/tabular/_box_like.py

View check run for this annotation

Codecov / codecov/patch

whitecanvas/layers/tabular/_box_like.py#L867

Added line #L867 was not covered by tests
_sd = np.std(x, ddof=ddof) * scale
return _mean - _sd, _mean + _sd

Expand All @@ -873,8 +873,10 @@
def err_by_se(self, scale: float = 1.0, *, ddof: int = 1) -> Self:
"""Set error to standard error."""

def err_func(x):
def err_func(x: np.ndarray):
_mean = np.mean(x)
if x.size <= ddof:
return _mean, _mean

Check warning on line 879 in whitecanvas/layers/tabular/_box_like.py

View check run for this annotation

Codecov / codecov/patch

whitecanvas/layers/tabular/_box_like.py#L879

Added line #L879 was not covered by tests
_er = np.std(x, ddof=ddof) / np.sqrt(len(x)) * scale
return _mean - _er, _mean + _er

Expand Down
Loading