Code to 50 temperature and humidity values,
import csv
import random
import time
# File name for saving the data
csv_filename = 'temperature_humidity_log.csv'
# Create and open the CSV file for writing
with open(csv_filename, mode='w', newline='') as file:
writer = csv.writer(file)
# Write the header
writer.writerow(["Timestamp", "Temperature (°C)", "Humidity (%)"])
# Generate and write 50 readings
for i in range(50):
# Simulate random sensor readings
temperature = round(random.uniform(20.0, 35.0), 2) # Simulate 20.0°C to 35.0°C
humidity = round(random.uniform(30.0, 70.0), 2) # Simulate 30% to 70% humidity
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
# Write the data row to the CSV file
writer.writerow([timestamp, temperature, humidity])
print(f"[{timestamp}] Temp: {temperature} °C | Humidity: {humidity} % recorded.")
# Wait 5 seconds before next reading
time.sleep(5)
print(f"\n✅ Data logging complete. 50 readings saved in '{csv_filename}'.")
Code to Visualize CSV Data with Explanations
import csv
import matplotlib.pyplot as plt
# File name to read data from
csv_filename = 'temperature_humidity_log.csv'
# Lists to store the CSV data
timestamps = []
temperatures = []
humidities = []
# Read the CSV file
with open(csv_filename, mode='r') as file:
reader = csv.DictReader(file)
for row in reader:
timestamps.append(row["Timestamp"])
temperatures.append(float(row["Temperature (°C)"]))
humidities.append(float(row["Humidity (%)"]))
# Plot 1: Temperature over Time (Line Plot)
plt.figure(figsize=(10,5))
plt.plot(timestamps, temperatures, marker='o', linestyle='-', color='red')
plt.title('Temperature Variation Over Time')
plt.xlabel('Time')
plt.ylabel('Temperature (°C)')
plt.xticks(rotation=45)
plt.grid(True)
plt.tight_layout()
plt.show()
# Purpose:
# This graph shows how temperature changes over time, useful to detect heating or cooling
trends.
# Plot 2: Humidity over Time (Line Plot)
plt.figure(figsize=(10,5))
plt.plot(timestamps, humidities, marker='x', linestyle='-', color='blue')
plt.title('Humidity Variation Over Time')
plt.xlabel('Time')
plt.ylabel('Humidity (%)')
plt.xticks(rotation=45)
plt.grid(True)
plt.tight_layout()
plt.show()
# Purpose:
# This graph tracks the environmental humidity changes, helping to monitor air moisture
conditions.
# Plot 3: Temperature vs Humidity (Scatter Plot)
plt.figure(figsize=(8,6))
plt.scatter(temperatures, humidities, color='green')
plt.title('Temperature vs Humidity')
plt.xlabel('Temperature (°C)')
plt.ylabel('Humidity (%)')
plt.grid(True)
plt.tight_layout()
plt.show()
# Purpose:
# This scatter plot explores the relationship between temperature and humidity,
# helping to find if higher temperatures correlate with higher or lower humidity levels.
# Plot 4: Dual Axis Plot (Temperature and Humidity Together)
fig, ax1 = plt.subplots(figsize=(10,5))
color = 'tab:red'
ax1.set_xlabel('Time')
ax1.set_ylabel('Temperature (°C)', color=color)
ax1.plot(timestamps, temperatures, color=color, label='Temperature')
ax1.tick_params(axis='y', labelcolor=color)
plt.xticks(rotation=45)
ax2 = ax1.twinx() # instantiate a second axis sharing the same x-axis
color = 'tab:blue'
ax2.set_ylabel('Humidity (%)', color=color)
ax2.plot(timestamps, humidities, color=color, linestyle='--', label='Humidity')
ax2.tick_params(axis='y', labelcolor=color)
plt.title('Temperature and Humidity Over Time')
fig.tight_layout()
plt.grid(True)
plt.show()
# Purpose:
# This dual-axis plot allows us to observe how temperature and humidity behave together over
the same time period.