Of course! Here is the Python code converted to use Plotly.
The main differences in the conversion are:
- Subplots: We use
make_subplots from plotly.subplots to create the 2x1 grid.
hue in Histogram: Seaborn's hue parameter is very convenient. In Plotly, you achieve the same effect by filtering the data yourself and adding a separate go.Histogram trace for each category ('Yes' and 'No').
- Layout: Plot styling (titles, axis types, ranges, ticks) is handled through the
fig.update_layout() and fig.update_xaxes/fig.update_yaxes methods, which provide fine-grained control over each subplot.
- Interactivity: The Matplotlib
Cursor is replaced by Plotly's superior built-in hover tooltips and crosshairs, which are enabled by default.
Plotly Conversion
This script is a complete, runnable example. It first generates some sample data that matches the structure of your prefiller_received DataFrame.
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# --- 1. Create Sample Data (to make the example runnable) ---
# This simulates the kind of data you might have.
np.random.seed(42)
num_points = 2000
reconstruction_time_ns = np.random.lognormal(mean=3, sigma=2, size=num_points) * 1e6
# Make most bytes_missing zero, but some with significant values
bytes_missing = np.zeros(num_points)
missing_indices = np.random.choice(num_points, size=int(num_points * 0.3), replace=False)
bytes_missing[missing_indices] = np.random.lognormal(mean=8, sigma=3, size=len(missing_indices))
prefiller_received = pd.DataFrame({
'reconstruction_time_ns': reconstruction_time_ns,
'bytes_missing': bytes_missing
})
# --- 2. Data Preparation (identical to your original code) ---
prefiller_received['reconstruction_time_ms'] = prefiller_received['reconstruction_time_ns'] / 1_000_000
prefiller_received['were_bytes_missing?'] = np.where(prefiller_received['bytes_missing'] > 0, 'Yes', 'No')
# --- 3. Plotly Figure Creation ---
# Define colors, similar to the original
hist_colors = {
'No': "#749940", # Greenish for "No" (good state)
'Yes': "#d6616b" # Reddish for "Yes" (problem state)
}
scatter_color = "#994047"
# Create a figure with 2 rows of subplots
fig = make_subplots(
rows=2, cols=1,
subplot_titles=(
"Distribution of Reconstruction Time",
"Reconstruction Time vs. Missing Bytes"
),
vertical_spacing=0.15 # Adjust spacing between plots
)
# --- Plot 1: Histogram ---
# To replicate seaborn's 'hue', we add one trace for each category.
# Trace for 'No' missing bytes
df_no = prefiller_received[prefiller_received['were_bytes_missing?'] == 'No']
fig.add_trace(go.Histogram(
x=df_no['reconstruction_time_ms'],
name='No Missing Bytes',
marker_color=hist_colors['No'],
opacity=0.75,
nbinsx=70
), row=1, col=1)
# Trace for 'Yes' missing bytes
df_yes = prefiller_received[prefiller_received['were_bytes_missing?'] == 'Yes']
fig.add_trace(go.Histogram(
x=df_yes['reconstruction_time_ms'],
name='Bytes Were Missing',
marker_color=hist_colors['Yes'],
opacity=0.75,
nbinsx=70
), row=1, col=1)
# --- Plot 2: Scatter Plot ---
fig.add_trace(go.Scatter(
x=prefiller_received['reconstruction_time_ms'],
y=prefiller_received['bytes_missing'],
mode='markers',
marker=dict(
color=scatter_color,
opacity=0.5, # Increased opacity slightly for better visibility
size=6 # `s=30` in matplotlib is roughly `size=sqrt(30)`~5.5
),
showlegend=False,
# Customize hover text
hovertemplate='Time: %{x:.2f} ms<br>Missing: %{y} bytes<extra></extra>'
), row=2, col=1)
# --- 4. Layout and Axis Configuration ---
# Global layout settings
fig.update_layout(
height=800,
width=800,
title_text="Prefiller Reconstruction Analysis",
barmode='overlay', # Overlay histograms to mimic seaborn
legend_title_text='Were Bytes Missing?'
)
# Configure axes for the top plot (Histogram)
fig.update_xaxes(
title_text="Reconstruction Time (ms)",
type='log',
tickvals=[0.5, 1, 5, 50, 200, 1000], # Custom ticks
row=1, col=1
)
fig.update_yaxes(title_text="Count", row=1, col=1)
# Configure axes for the bottom plot (Scatter)
xticks = [1, 10, 50, 100, 1000]
yticks_bytes = [0, 256, 1024, 10*1024, 1024*1024, 4*1024*1024]
ytick_labels = ['0 B', '256 B', '1 KiB', '10 KiB', '1 MiB', '4 MiB']
fig.update_xaxes(
title_text="Reconstruction Time (ms)",
type='log',
tickvals=xticks,
range=[np.log10(0.8), np.log10(prefiller_received['reconstruction_time_ms'].max()*1.1)], # Match xlim(left=1)
row=2, col=1
)
fig.update_yaxes(
title_text="Missing Bytes",
type='symlog', # Use 'symlog' for symmetrical log scale
tickvals=yticks_bytes,
ticktext=ytick_labels,
# Set range, note that symlog can handle negative values
# Plotly's autorange usually works well, but we can set it to match ylim(-0.5)
range=[-0.5, np.log10(prefiller_received['bytes_missing'].max()*1.5)],
row=2, col=1
)
# --- 5. Show the Figure ---
fig.show()