If the report_date field is already in a timestamp format, you don't need to convert it to a datetime object explicitly. You can directly use it for plotting. However, timestamps can sometimes be difficult to interpret on a plot, so you might still want to format them for better readability.
Here’s the updated code to handle report_date as a timestamp:
import duckdb
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Connect to the DuckDB database
db_path = "../weather-4.duckdb"
conn = duckdb.connect(db_path)
# Define the station you want to filter
station_name = "YOUR_STATION_NAME" # Replace with the desired station name
# Query the data for the given station
query = f"""
SELECT report_date, hour, temperature_F
FROM weather
WHERE station = '{station_name}'
"""
data = conn.execute(query).fetchdf()
# Close the connection
conn.close()
# Extract the necessary columns
dates = data['report_date'] # Already in timestamp format
hours = data['hour']
temperatures = data['temperature_F']
# Create a 3D plot
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
# Plot the data
sc = ax.scatter(dates, hours, temperatures, c=temperatures, cmap='viridis', marker='o')
# Set labels
ax.set_xlabel('Report Date (Timestamp)')
ax.set_ylabel('Hour')
ax.set_zlabel('Temperature (°F)')
ax.set_title(f"3D Plot of Temperature for Station: {station_name}")
# Add a color bar to show the temperature scale
cbar = plt.colorbar(sc, ax=ax, pad=0.1)
cbar.set_label('Temperature (°F)')
# Rotate the plot for better visualization
ax.view_init(elev=20, azim=120)
# Show the plot
plt.show()
Key Changes:
- No Conversion of
report_date: Since report_date is already in timestamp format, it is used directly for plotting.
- Color Bar: Added a color bar (
plt.colorbar) to provide a visual reference for the temperature values.
- Improved Labels: Updated the x-axis label to indicate that
report_date is in timestamp format.
Notes:
- If the timestamps are too granular (e.g., include seconds and milliseconds), the x-axis labels might look cluttered. You can format the timestamps for better readability using
pd.to_datetime and formatting options.
- If the dataset is large, consider limiting the number of rows in the query (e.g.,
LIMIT 1000) to improve performance.
Let me know if you need help with further customization!