Skip to content

Instantly share code, notes, and snippets.

@acssantos
Last active May 24, 2022 20:33
Show Gist options
  • Save acssantos/3108539189e60e4b059130259d21f5a9 to your computer and use it in GitHub Desktop.
Save acssantos/3108539189e60e4b059130259d21f5a9 to your computer and use it in GitHub Desktop.
Code to make a histogram plot with X axes in the logarithmic scale
import numpy as np
import plotly.graph_objects as go
def log_histogram(data_list, names=None, bins=None):
""" Plot histogram in log scale bins
It constructs the numpy histogram with logarithm of data
and plots a bar graph with customized ticks and hover.
The plotly library does not have the option of ploting logscale
histograms.
Params
------
data_list: list[np.array]
Array to construct histogram
names: list[str]
Names for legend of data. Optional
bins: array
Custom array of bin edges to construct the histogram count,
by default it uses 'doane' automatic method from numpy.
Should consider the log of data.
Returns
-------
fig: plotly.graph_objs._figure.Figure
Figure objetct with the histogram plot. To visualize use: fig.show()
bins: array
Return the bin edges.
"""
fig = go.Figure()
if names is None:
names = [None]*len(data_list)
print(names)
fig_data = []
histograms = {}
for i, data in enumerate(data_list):
log_data = np.log1p(data)
# log_data = data
if bins is None and i == 0:
counts, bins = np.histogram(log_data, bins='doane', density=False)
else:
counts, bins = np.histogram(log_data, bins=bins, density=False)
center_bins = 0.5 * (bins[:-1] + bins[1:])
# Percentage
counts = counts/np.sum(counts)
histograms[names[i]] = counts
#Custom data should be of shape [len(x), cols]
real_bins = np.exp(bins)-1
ranges = np.stack((real_bins[:-1], real_bins[1:]), axis=-1)
fig.add_trace(go.Bar(x=center_bins, y=counts, name=names[i]))
fig.update_traces(customdata=ranges,
hovertemplate=
"bin:%{customdata[0]:.3f} - %{customdata[1]:.3f}<br><b>Count(%):%{y:.3f}</b>")
#fig_data.append(go.Bar(x=center_bins, y=counts, name=names[i])
#fig = go.Figure(data=fig_data)
fig.update_layout(
xaxis = dict(
tickmode = 'array',
tickvals = bins[::2],
ticktext = np.round(np.exp(bins[::2]),0)
)
)
# fig.update_layout(barmode='stack')
return fig, bins, histograms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment