I have a duckdb database named weather-4.duckdb
There is a table named weather and fields called station, report date, hour, and temperature_F.
Can you plot temperature over time for a given station?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Let's create a Python script that uses DuckDB to query the weather data and matplotlib to plot the temperature over time for a specific station. Here's a complete solution:
python
import duckdb
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime
def plot_temperature(station_id, db_path='weather-4.duckdb'):
try:
# Connect to the DuckDB database
conn = duckdb.connect(db_path, read_only=True)
# Query the data for the specified station
query = """
SELECT report_date, hour, temperature_F
FROM weather
WHERE station = ?
ORDER BY report_date, hour
"""
# Execute query and load results into a pandas DataFrame
df = conn.execute(query, [station_id]).fetchdf()
if df.empty:
print(f"No data found for station {station_id}")
return
# Combine date and hour into a single datetime column
df['datetime'] = pd.to_datetime(
df['report_date'].astype(str) + ' ' + df['hour'].astype(str).str.zfill(2) + ':00:00'
)
# Create the plot
plt.figure(figsize=(12, 6))
plt.plot(df['datetime'], df['temperature_F'], '-b', label='Temperature (°F)')
# Customize the plot
plt.title(f'Temperature Over Time - Station {station_id}')
plt.xlabel('Date and Time')
plt.ylabel('Temperature (°F)')
plt.grid(True)
plt.legend()
# Rotate x-axis labels for better readability
plt.xticks(rotation=45)
# Adjust layout to prevent label cutoff
plt.tight_layout()
# Show the plot
plt.show()
except Exception as e:
print(f"An error occurred: {str(e)}")
finally:
# Close the database connection
if 'conn' in locals():
conn.close()
# Example usage
if __name__ == "__main__":
# Replace 'YOUR_STATION_ID' with the actual station ID you want to plot
station_id = 'YOUR_STATION_ID'
plot_temperature(station_id)
To use this script, you'll need to:
Install the required packages if you haven't already:
bash
pip install duckdb pandas matplotlib
Modify the script by replacing 'YOUR_STATION_ID' with the actual station ID you want to plot.
Make sure the database file path is correct (default is 'weather-4.duckdb' in the current directory).
This script will:
Connect to your DuckDB database
Query the temperature data for the specified station
Create a datetime series by combining the report_date and hour
Plot the temperature over time
Add appropriate labels, title, and grid
Display the plot
Additional features and modifications you might want to consider:
To see what stations are available in your database, you can add this function:
python
def list_stations(db_path='weather-4.duckdb'):
try:
conn = duckdb.connect(db_path, read_only=True)
query = "SELECT DISTINCT station FROM weather ORDER BY station"
stations = conn.execute(query).fetchall()
print("Available stations:")
for station in stations:
print(station[0])
except Exception as e:
print(f"An error occurred: {str(e)}")
finally:
if 'conn' in locals():
conn.close()
# Add this to the example usage
if __name__ == "__main__":
list_stations()
station_id = 'YOUR_STATION_ID'
plot_temperature(station_id)
To add a date range filter, you could modify the function to accept start and end dates:
python
def plot_temperature(station_id, start_date=None, end_date=None, db_path='weather-4.duckdb'):
try:
conn = duckdb.connect(db_path, read_only=True)
query = """
SELECT report_date, hour, temperature_F
FROM weather
WHERE station = ?
"""
params = [station_id]
if start_date:
query += " AND report_date >= ?"
params.append(start_date)
if end_date:
query += " AND report_date <= ?"
params.append(end_date)
query += " ORDER BY report_date, hour"
df = conn.execute(query, params).fetchdf()
# ... rest of the function remains the same
To save the plot instead of displaying it, add this before plt.show():