You're an expert in Python and software engineering best practices.
I have this function (and other similar functions) that is used to plot a chart in Plotly. However, a good chunk of the function (after the fig = go.Figure(data=traces, layout=layout line) is duplicated in all the other functions. What would you recommend to address this duplication? Should we create another function?
Here's the function in its entirety.
def plot_trend_hourly_comparison_plotly(
df,
column_name,
bucket_hour_size=1,
path_save_dir=None,
filename=None,
title="Hourly Trend Comparison",
running_in_aws=False,
bucket_name=None,
session_id=None,
user_id=None,
):
"""
Generates an interactive strip plot for hourly trend comparison across multiple days.
Args:
df (pandas.DataFrame): A DataFrame containing the data to be visualized.
column_name (str): The name of the column in the DataFrame to visualize.
Other arguments are similar to your existing function for handling file saving and AWS integration.
Returns:
plotly.graph_objects.Figure: An interactive Plotly strip plot figure.
"""
# Extract the column and set time as index
time_data = df[["Time", column_name]].copy()
time_data.set_index("Time", inplace=True)
# Normalize the time data to extract the hour component
time_data['Hour'] = time_data.index.hour
# Group data by the hour of the day
hourly_groups = time_data.groupby('Hour')
# Creating traces for each hour
traces = []
for hour, group in hourly_groups:
for _, row in group.iterrows():
value = row[column_name]
traces.append(
go.Scatter(
x=[hour, hour + bucket_hour_size],
y=[value, value],
mode='lines',
line=dict(width=2, color='black'),
opacity=0.1
)
)
# Setting up the Plotly figure
layout = go.Layout(
title=title,
xaxis=dict(title='Hour of Day', range=[0, 24]),
yaxis=dict(title='Value'),
showlegend=False
)
fig = go.Figure(data=traces, layout=layout)
if path_save_dir is None:
path_save_dir = Path.cwd()
else:
path_save_dir = Path(path_save_dir)
# Save plot to an in-memory string file first
in_memory_string_file = io.StringIO()
pio.write_html(fig, in_memory_string_file)
html_str = in_memory_string_file.getvalue()
# Convert the string to bytes and write to BytesIO
in_memory_file = io.BytesIO()
in_memory_file.write(html_str.encode("utf-8"))
in_memory_file.seek(0)
unique_id = str(uuid.uuid4().hex)
logging.info(f"Filename: {filename}")
if filename is None:
filename = f"pct_vol_{unique_id}.html"
else:
filename = f"{filename}_{unique_id}.html"
# Check that the filename is not too long. Must be <= 64 characters
if len(filename) > 64:
logging.warning(f"Filename too long: {filename}. Truncating to 64 characters.")
filename = filename[-64:]
logging.info(f"Filename: {filename}, Filename Charcount: {len(filename)}")
if running_in_aws:
bucket_name = "chartuploadbucket"
# Save the file to S3
s3_client = boto3.client("s3")
s3_client.upload_fileobj(in_memory_file, bucket_name, f"{filename}")
print(f"Plot saved to S3: s3://{bucket_name}/{filename}")
save_htlm_s3_uid_to_db(bucket_name, filename, session_id, user_id)
else:
# Save locally if S3 details are not provided
local_path = Path(path_save_dir) / filename
with open(local_path, "wb") as f:
f.write(in_memory_file.getvalue())
print(f"Plot saved locally: {local_path}")