Skip to content

Commit 3acbd3c

Browse files
Update histograms.md
'Accessing the counts (y-axis) values' - use example with numpy instead of pandas
1 parent d83b1b0 commit 3acbd3c

File tree

1 file changed

+7
-16
lines changed

1 file changed

+7
-16
lines changed

Diff for: doc/python/histograms.md

+7-16
Original file line numberDiff line numberDiff line change
@@ -69,29 +69,20 @@ fig = px.histogram(df, x="total_bill", nbins=20)
6969
fig.show()
7070
```
7171

72-
#### Accessing the y-axis values
72+
#### Accessing the counts (y-axis) values
7373

74-
JavaScript calculates the y-axis (count) values on the fly in the browser, so it's not accessible in the `fig`. You can manually calculate it using `pandas.cut` or `np.digitize`.
74+
JavaScript calculates the y-axis (count) values on the fly in the browser, so it's not accessible in the `fig`. You can manually calculate it using `np.histogram`.
7575

7676
```python
7777
import plotly.express as px
78-
import pandas as pd
78+
import numpy as np
7979

8080
df = px.data.tips()
81+
# create the bins
82+
counts, bins = np.histogram(df.total_bill, bins=range(0, 60, 5))
83+
bins = 0.5 * (bins[:-1] + bins[1:])
8184

82-
# create the bins; use the `range` to get the same bin size as in the histogram in the previous section.
83-
df["total_bill_bins"] = pd.cut(df.total_bill, bins=range(0, 60, 5), right=False)
84-
85-
# calculate counts
86-
df_counts = df.pivot_table(index="total_bill_bins", values="size", aggfunc='count').reset_index()
87-
df_counts.rename(columns={"size": "count"}, inplace=True)
88-
89-
# sort, then convert to string
90-
df_counts = df_counts.sort_values(by="total_bill_bins")
91-
df_counts["total_bill_bins"] = df_counts["total_bill_bins"].astype(str)
92-
93-
# display calculated counts on the bar chart
94-
fig = px.bar(df_counts, x="total_bill_bins", y="count")
85+
fig = px.bar(x=bins, y=counts, labels={'x':'total_bill', 'y':'count'})
9586
fig.show()
9687
```
9788

0 commit comments

Comments
 (0)