Requirements
- Python: Make sure you have Python installed (version 3.6 or above).
- Libraries: Install the following libraries using pip:bashCopy code
pip install matplotlib numpy
Step 1: Set Up the Data Structure
We’ll use a simple dictionary to store the fitness data.
import random
import time
fitness_data = {
"steps": 0,
"heart_rate": 0,
"calories_burned": 0
}
Step 2: Simulate Fitness Tracking
We’ll create functions to simulate updating steps, heart rate, and calories burned.
def update_steps():
# Simulate step counting
steps = random.randint(0, 100)
fitness_data["steps"] += steps
return steps
def update_heart_rate():
# Simulate heart rate measurement
heart_rate = random.randint(60, 100)
fitness_data["heart_rate"] = heart_rate
return heart_rate
def update_calories_burned(steps):
# Simple formula for calories burned (approx.)
calories = steps * 0.04
fitness_data["calories_burned"] += calories
return calories
Step 3: Main Loop to Collect Data
Now we’ll create a loop to collect data at regular intervals.
def collect_data(duration=10):
start_time = time.time()
while (time.time() - start_time) < duration:
steps = update_steps()
heart_rate = update_heart_rate()
calories = update_calories_burned(steps)
print(f"Steps: {fitness_data['steps']}, Heart Rate: {heart_rate} bpm, Calories Burned: {fitness_data['calories_burned']:.2f}")
time.sleep(1) # Collect data every second
Step 4: Visualizing the Data
To visualize the data, we can create a simple graph using matplotlib
.
import matplotlib.pyplot as plt
def plot_data():
# Data for plotting
steps = []
heart_rates = []
calories = []
for _ in range(10):
steps.append(fitness_data["steps"])
heart_rates.append(fitness_data["heart_rate"])
calories.append(fitness_data["calories_burned"])
time.sleep(1) # Simulate time passing
# Plotting
plt.figure(figsize=(10, 5))
plt.subplot(1, 3, 1)
plt.plot(steps, label='Steps', color='blue')
plt.title('Steps Over Time')
plt.xlabel('Time (s)')
plt.ylabel('Steps')
plt.subplot(1, 3, 2)
plt.plot(heart_rates, label='Heart Rate', color='red')
plt.title('Heart Rate Over Time')
plt.xlabel('Time (s)')
plt.ylabel('Heart Rate (bpm)')
plt.subplot(1, 3, 3)
plt.plot(calories, label='Calories Burned', color='green')
plt.title('Calories Burned Over Time')
plt.xlabel('Time (s)')
plt.ylabel('Calories')
plt.tight_layout()
plt.show()
Step 5: Putting It All Together
Finally, we’ll run the data collection and plotting functions.
if __name__ == "__main__":
collect_data(duration=10) # Collect data for 10 seconds
plot_data() # Plot the collected data
Running the Tracker
- Save your script as
fitness_tracker.py
. - Run it using:bashCopy code
python fitness_tracker.py
This will simulate tracking fitness data and visualize the results after collecting data for 10 seconds.
Leave a Reply