Skip to content

Commit 82c20a0

Browse files
committed
Fix geom_histogram and mapping to the weight aesthetic
Also fixes the same problem for geom_bindot. fixes #936
1 parent 6615143 commit 82c20a0

File tree

5 files changed

+20
-4
lines changed

5 files changed

+20
-4
lines changed

doc/changelog.qmd

+3
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,9 @@ title: Changelog
126126
the themeables. This affected `theme_xkcd` and any `theme` settings that tried to slide the
127127
text / background into the panel.
128128

129+
- Fixed bug in [](:class:`~plotnine.geom_histogram`) where mapping to the `weight` aesthetic
130+
lead to an error. {{< issue 936 >}}
131+
129132
## v0.14.5
130133
(2025-01-02)
131134
[![](https://zenodo.org/badge/DOI/10.5281/zenodo.14587381.svg)](https://doi.org/10.5281/zenodo.14587381)

plotnine/stats/binning.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,10 @@ def assign_bins(
165165
if weight is None:
166166
weight = np.ones(len(x))
167167
else:
168-
weight = np.asarray(weight)
168+
# If weight is a dtype that isn't writeable
169+
# and does not own it's memory. Using a list
170+
# as an intermediate easily solves this.
171+
weight = np.array(list(weight))
169172
weight[np.isnan(weight)] = 0
170173

171174
bin_idx = pd.cut(

plotnine/stats/stat_bindot.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -281,9 +281,7 @@ def densitybin(
281281
if all(pd.isna(x)):
282282
return pd.DataFrame()
283283

284-
if weight is None:
285-
weight = np.ones(len(x))
286-
weight = np.asarray(weight)
284+
weight = np.ones(len(x)) if weight is None else np.array(list(weight))
287285
weight[np.isnan(weight)] = 0
288286

289287
if rangee is None:
Loading

tests/test_geom_bar_col_histogram.py

+12
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,15 @@ def test_freedman_diaconis_bins():
9999
iqr1 = freedman_diaconis_bins(a1)
100100
iqr2 = freedman_diaconis_bins(a2)
101101
assert iqr1 == iqr2
102+
103+
104+
def test_histogram_weights():
105+
data = pd.DataFrame(
106+
{
107+
"x": list(range(1, 6)),
108+
"w": list(range(1, 6)),
109+
}
110+
)
111+
112+
p = ggplot(data, aes("x", weight="w")) + geom_histogram(bins=5)
113+
assert p == "histogram_weights"

0 commit comments

Comments
 (0)