Last active
March 10, 2022 04:42
-
-
Save makvoid/fe4b7ca20da65f6ed06534381064e3c5 to your computer and use it in GitHub Desktop.
AHT20 average_date, get_entries, plot_data methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def average_date(date, entries): | |
# Get a list of all entries for this date | |
events = list(filter(lambda x: (x['date'][0:10] == date), entries)) | |
return { | |
'date': pd.to_datetime(date), | |
'temperature': sum(float(e['temperature']) for e in events) / len(events), | |
'humidity': sum(float(e['humidity']) for e in events) / len(events) | |
} | |
# Returns entries as DataFrames | |
def get_entries(location): | |
# load entries from file | |
with open("entries.json", "r") as f: | |
all_entries = json.loads(f.read()) | |
# Filter entries by our location | |
entries = list(filter(lambda e: e['location'] == location, all_entries)) | |
# Ensure at least one entry is returned for this location | |
if len(entries) == 0: | |
print('Error: No entries found for location ({}). Try another?'.format(location)) | |
sys.exit(1) | |
# Get a set/list of unique dates in YYYY-MM-DD format from the entries | |
dates = set(map(lambda e: e['date'][0:10], entries)) | |
# Get the average temperature and humidity per day and convert to a DataFrame | |
df = pd.DataFrame(map(lambda date: average_date(date, entries), dates)) | |
# Sort values by the date and set it as the index | |
df = df.sort_values('date', ascending=True).set_index('date') | |
# Use the same DF for both, but rename the subject field as needed | |
return { | |
'temperature': df.rename(columns={'temperature': 'value'}), | |
'humidity': df.rename(columns={'humidity': 'value'}) | |
} | |
# Plot dataset on a axis with it's display information | |
def plot_data(data, ax, x_label, y_label, color, alpha = 1): | |
color = 'tab:{}'.format(color) | |
# Set labels | |
ax.set_xlabel(x_label) | |
ax.set_ylabel(y_label, color=color) | |
ax.tick_params(axis='y', labelcolor=color) | |
# Plot data | |
ax.plot(data.index, data.value, marker='o', color=color, alpha=alpha) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment