import plotly.graph_objects as go
import numpy as np
import random
np.random.seed(42)
# covariance matrix
mean = [0, 0]
cov = [[1, 0], [0, 100]] # diagonal covariance
# データの準備(xとyの座標)
num_points = np.int64(np.linspace(1, 1200, 13))
# byte list
kb_svg = []
kb_png = []
kb_pdf = []
# 散布図の作成とSVGへの保存
for num in num_points:
x, y = np.random.multivariate_normal(mean, cov, num).T
trace = go.Scatter(x=x, y=y, mode="markers", marker=dict(size=10))
fig = go.Figure(data=[trace])
# SVGとして保存
svg_content = fig.to_image(format="svg")
png_content = fig.to_image(format="png")
pdf_content = fig.to_image(format="pdf")
# ファイルサイズを取得(KBに換算)
kb_svg.append(len(svg_content) / 1024)
kb_png.append(len(png_content) / 1024)
kb_pdf.append(len(pdf_content) / 1024)
del x, y, svg_content, png_content, pdf_content
# ----------------------------
# Create line plot for file sizes
# ----------------------------
# color setup
okabe_ito_colors = [
"#000000",
"#E69F00",
"#56B4E9",
"#009E73",
"#F0E442",
"#0072B2",
"#D55E00",
"#CC79A7",
]
fig_bytes = go.Figure()
# Add SVG line
fig_bytes.add_trace(
go.Scatter(
x=num_points,
y=kb_svg,
mode="lines+markers",
name="SVG File Size",
line=dict(color=okabe_ito_colors[1], width=2),
marker=dict(size=6),
)
)
# Add PNG line
fig_bytes.add_trace(
go.Scatter(
x=num_points,
y=kb_png,
mode="lines+markers",
name="PNG File Size",
line=dict(color=okabe_ito_colors[2], width=2),
marker=dict(size=6),
)
)
# Add PDF line
fig_bytes.add_trace(
go.Scatter(
x=num_points,
y=kb_pdf,
mode="lines+markers",
name="PDF File Size",
line=dict(color=okabe_ito_colors[3], width=2),
marker=dict(size=6),
)
)
# Update layout
fig_bytes.update_layout(
title=dict(
text="Plotly-based File Size Comparison: SVG, PNG vs PDF",
x=0.075,
xanchor="left",
y=0.95,
yanchor="top",
font=dict(size=20),
),
margin=dict(t=80, b=40),
xaxis_title="Number of Data Points",
yaxis_title="File Size (KB)",
hovermode="x unified",
template="plotly_white",
width=640,
height=400,
legend=dict(
orientation="h", # horizontal layout
yanchor="bottom",
y=1.02, # slightly above the plot
xanchor="center",
x=0.5, # center-align
),
)
# Update axes for better readability
fig_bytes.update_xaxes(showgrid=True, gridwidth=1, gridcolor="lightgray")
fig_bytes.update_yaxes(showgrid=True, gridwidth=1, gridcolor="lightgray")
# Show the plot
fig_bytes.show()