Skip to content

Commit

Permalink
Format with Black autoformatter
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Jun 13, 2023
1 parent 8633331 commit 78e652a
Show file tree
Hide file tree
Showing 9 changed files with 211 additions and 150 deletions.
44 changes: 33 additions & 11 deletions src/stravavis/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,35 +15,57 @@ def main():
parser.add_argument(
"--lon_min",
type=float,
help="Minimum longitude for plot_map (values less than this are removed from the data)",
help="Minimum longitude for plot_map "
"(values less than this are removed from the data)",
)
parser.add_argument(
"--lon_max",
type=float,
help="Maximum longitude for plot_map (values greater than this are removed from the data)",
help="Maximum longitude for plot_map "
"(values greater than this are removed from the data)",
)
parser.add_argument(
"--lat_min",
type=float,
help="Minimum latitude for plot_map (values less than this are removed from the data)",
help="Minimum latitude for plot_map "
"(values less than this are removed from the data)",
)
parser.add_argument(
"--lat_max",
type=float,
help="Maximum latitude for plot_map (values greater than this are removed from the data)",
help="Maximum latitude for plot_map "
"(values greater than this are removed from the data)",
)
parser.add_argument(
"--bbox", help="Shortcut for comma-separated LON_MIN,LAT_MIN,LON_MAX,LAT_MAX"
)
parser.add_argument("--alpha", default=0.4, help="Line transparency. 0 = Fully transparent, 1 = No transparency")
parser.add_argument(
"--alpha",
default=0.4,
help="Line transparency. 0 = Fully transparent, 1 = No transparency",
)
parser.add_argument("--linewidth", default=0.4, help="Line width")
parser.add_argument("--activities_path", help="Path to activities.csv from Strava bulk export zip")
parser.add_argument("--year_min", help="The minimum year to use for the calendar heatmap.")
parser.add_argument("--year_max", help="The maximum year to use for the calendar heatmap.")
parser.add_argument("--max_dist", help="Maximum daily distance for the calendar heatmap; values above this will be capped.")
parser.add_argument(
"--activities_path", help="Path to activities.csv from Strava bulk export zip"
)
parser.add_argument(
"--year_min", help="The minimum year to use for the calendar heatmap."
)
parser.add_argument(
"--year_max", help="The maximum year to use for the calendar heatmap."
)
parser.add_argument(
"--max_dist",
help="Maximum daily distance for the calendar heatmap; "
"values above this will be capped.",
)
parser.add_argument("--fig_height", help="Figure height for the calendar heatmap.")
parser.add_argument("--fig_width", help="Figure width for the calendar heatmap.")
parser.add_argument("--local_timezone", help="Timezone for determining local times for activities. See pytz.all_timezones for a list of all timezones.")
parser.add_argument(
"--local_timezone",
help="Timezone for determining local times for activities. "
"See pytz.all_timezones for a list of all timezones.",
)
args = parser.parse_args()

# Expand "~" or "~user"
Expand Down Expand Up @@ -114,7 +136,7 @@ def main():
outfile = f"{args.output_prefix}-calendar.png"
plot_calendar(activities, output_file=outfile)
print(f"Saved to {outfile}")

print("Plotting dumbbell...")
outfile = f"{args.output_prefix}-dumbbell.png"
plot_dumbbell(activities, output_file=outfile)
Expand Down
38 changes: 22 additions & 16 deletions src/stravavis/plot_calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,36 @@
import matplotlib.pyplot as plt
import pandas as pd

def plot_calendar(activities, year_min=None, year_max=None, max_dist=None,
fig_height = 15, fig_width = 9, output_file='calendar.png'):

def plot_calendar(
activities,
year_min=None,
year_max=None,
max_dist=None,
fig_height=15,
fig_width=9,
output_file="calendar.png",
):
# Create a new figure
plt.figure()

# Process data
activities['Activity Date'] = pd.to_datetime(activities['Activity Date'])
activities['date'] = activities['Activity Date'].dt.date
activities = activities.groupby(['date'])['Distance'].sum()
activities["Activity Date"] = pd.to_datetime(activities["Activity Date"])
activities["date"] = activities["Activity Date"].dt.date
activities = activities.groupby(["date"])["Distance"].sum()
activities.index = pd.to_datetime(activities.index)
activities.clip(0, max_dist, inplace=True)

if year_min:
activities = activities[activities.index.year>=year_min]
activities = activities[activities.index.year >= year_min]

if year_max:
activities = activities[activities.index.year<=year_max]
activities = activities[activities.index.year <= year_max]

# Create heatmap
fig, ax = calmap.calendarplot(
data = activities
)

fig, ax = calmap.calendarplot(data=activities)

# Save plot
fig.set_figheight(fig_height)
fig.set_figwidth(fig_width)
fig.savefig(output_file, dpi = 600)
fig.savefig(output_file, dpi=600)
113 changes: 68 additions & 45 deletions src/stravavis/plot_dumbbell.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,61 +12,84 @@
theme,
theme_bw,
xlab,
ylab
)
ylab,
)

def plot_dumbbell(activities, year_min=None, year_max=None, local_timezone=None,
fig_height = 34, fig_width = 34, output_file='dumbbell.png'):


def plot_dumbbell(
activities,
year_min=None,
year_max=None,
local_timezone=None,
fig_height=34,
fig_width=34,
output_file="dumbbell.png",
):
# Convert activity start date to datetime
activities['Activity Date'] = pd.to_datetime(activities['Activity Date'])
activities["Activity Date"] = pd.to_datetime(activities["Activity Date"])

# Convert to local timezone (if given)
if local_timezone:
activities['Activity Date'] = (pd.to_datetime(activities['Activity Date'])
.dt.tz_localize(tz='UTC', nonexistent='NaT', ambiguous='NaT')
.dt.tz_convert(local_timezone))

activities["Activity Date"] = (
pd.to_datetime(activities["Activity Date"])
.dt.tz_localize(tz="UTC", nonexistent="NaT", ambiguous="NaT")
.dt.tz_convert(local_timezone)
)

# Get activity start and end times
activities['start'] = activities['Activity Date']
activities['duration'] = 0
activities["start"] = activities["Activity Date"]
activities["duration"] = 0
for i in range(len(activities)):
activities['duration'][i] = pd.Timedelta(activities['Elapsed Time'][i], unit= "s")
activities['end'] = activities['start'] + activities['duration']

activities["duration"][i] = pd.Timedelta(
activities["Elapsed Time"][i], unit="s"
)
activities["end"] = activities["start"] + activities["duration"]

# Remove activities outside the year_min -> year_max window
activities['year'] = activities['Activity Date'].dt.year
activities["year"] = activities["Activity Date"].dt.year

if year_min:
activities = activities[activities['year']>=year_min]
activities = activities[activities["year"] >= year_min]

if year_max:
activities = activities[activities['year']<=year_max]
activities = activities[activities["year"] <= year_max]

# Get day of year and time of day data
activities['dayofyear'] = activities['Activity Date'].dt.dayofyear
activities['start_time'] = activities['start'].dt.time
activities['end_time'] = activities['end'].dt.time
activities['x'] = (activities['start'].dt.hour
+ activities['start'].dt.minute/60
+ activities['start'].dt.second/60/60)
activities['xend'] = (activities['end'].dt.hour
+ activities['end'].dt.minute/60
+ activities['end'].dt.second/60/60)

activities["dayofyear"] = activities["Activity Date"].dt.dayofyear
activities["start_time"] = activities["start"].dt.time
activities["end_time"] = activities["end"].dt.time
activities["x"] = (
activities["start"].dt.hour
+ activities["start"].dt.minute / 60
+ activities["start"].dt.second / 60 / 60
)
activities["xend"] = (
activities["end"].dt.hour
+ activities["end"].dt.minute / 60
+ activities["end"].dt.second / 60 / 60
)

# Create plotnine / ggplot
p = (ggplot(activities) +
geom_segment(aes(x="x", y="dayofyear", xend="xend", yend="dayofyear"), size = 0.1) +
geom_point(aes("x", "dayofyear"), size = 0.05) +
geom_point(aes("xend", "dayofyear"), size = 0.05) +
facet_grid('.~year') +
scale_x_continuous(breaks = [0, 6, 12, 18, 24], labels = ["12am", "6am", "12pm", "6pm", ""]) +
scale_y_continuous(breaks = [1, 100, 200, 300, 365]) +
xlab("Time of Day") +
ylab("Day of Year") +
theme_bw() +
theme(plot_background = element_rect(fill = "white"), panel_grid_major_y = element_blank())
p = (
ggplot(activities)
+ geom_segment(
aes(x="x", y="dayofyear", xend="xend", yend="dayofyear"), size=0.1
)
+ geom_point(aes("x", "dayofyear"), size=0.05)
+ geom_point(aes("xend", "dayofyear"), size=0.05)
+ facet_grid(".~year")
+ scale_x_continuous(
breaks=[0, 6, 12, 18, 24], labels=["12am", "6am", "12pm", "6pm", ""]
)
+ scale_y_continuous(breaks=[1, 100, 200, 300, 365])
+ xlab("Time of Day")
+ ylab("Day of Year")
+ theme_bw()
+ theme(
plot_background=element_rect(fill="white"),
panel_grid_major_y=element_blank(),
)
)

# Save plot
p.save(output_file, width=fig_width, height=fig_height, units = "cm", dpi=600)
p.save(output_file, width=fig_width, height=fig_height, units="cm", dpi=600)
43 changes: 22 additions & 21 deletions src/stravavis/plot_elevations.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,40 @@
import math

import matplotlib.pyplot as plt
import seaborn as sns

def plot_elevations(df, output_file = 'elevations.png'):

def plot_elevations(df, output_file="elevations.png"):
# Create a new figure
plt.figure()

# Compute activity start times (for facet ordering)
start_times = df.groupby('name').agg({'time': 'min'}).reset_index().sort_values('time')
start_times = (
df.groupby("name").agg({"time": "min"}).reset_index().sort_values("time")
)
ncol = math.ceil(math.sqrt(len(start_times)))

# Create facets
p = sns.FacetGrid(
data = df,
col = 'name',
col_wrap = ncol,
col_order = start_times['name'],
sharex = False,
sharey = True,
)
data=df,
col="name",
col_wrap=ncol,
col_order=start_times["name"],
sharex=False,
sharey=True,
)

# Add activities
p = p.map(
plt.plot, "dist", "ele", color = 'black', linewidth = 4
)
p = p.map(plt.plot, "dist", "ele", color="black", linewidth=4)

# Update plot aesthetics
p.set(xlabel = None)
p.set(ylabel = None)
p.set(xticks = [])
p.set(yticks = [])
p.set(xticklabels = [])
p.set(yticklabels = [])
p.set_titles(col_template = '', row_template = '')
sns.despine(left = True, bottom = True)
plt.subplots_adjust(left = 0.05, bottom = 0.05, right = 0.95, top = 0.95)
p.set(xlabel=None)
p.set(ylabel=None)
p.set(xticks=[])
p.set(yticks=[])
p.set(xticklabels=[])
p.set(yticklabels=[])
p.set_titles(col_template="", row_template="")
sns.despine(left=True, bottom=True)
plt.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95)
plt.savefig(output_file)
45 changes: 23 additions & 22 deletions src/stravavis/plot_facets.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,40 @@
import math

import matplotlib.pyplot as plt
import seaborn as sns

def plot_facets(df, output_file = 'plot.png'):

def plot_facets(df, output_file="plot.png"):
# Create a new figure
plt.figure()

# Compute activity start times (for facet ordering)
start_times = df.groupby('name').agg({'time': 'min'}).reset_index().sort_values('time')
start_times = (
df.groupby("name").agg({"time": "min"}).reset_index().sort_values("time")
)
ncol = math.ceil(math.sqrt(len(start_times)))

# Create facets
p = sns.FacetGrid(
data = df,
col = 'name',
col_wrap = ncol,
col_order = start_times['name'],
sharex = False,
sharey = False,
)
data=df,
col="name",
col_wrap=ncol,
col_order=start_times["name"],
sharex=False,
sharey=False,
)

# Add activities
p = p.map(
plt.plot, "lon", "lat", color = 'black', linewidth = 4
)
p = p.map(plt.plot, "lon", "lat", color="black", linewidth=4)

# Update plot aesthetics
p.set(xlabel = None)
p.set(ylabel = None)
p.set(xticks = [])
p.set(yticks = [])
p.set(xticklabels = [])
p.set(yticklabels = [])
p.set_titles(col_template = '', row_template = '')
sns.despine(left = True, bottom = True)
plt.subplots_adjust(left = 0.05, bottom = 0.05, right = 0.95, top = 0.95)
p.set(xlabel=None)
p.set(ylabel=None)
p.set(xticks=[])
p.set(yticks=[])
p.set(xticklabels=[])
p.set(yticklabels=[])
p.set_titles(col_template="", row_template="")
sns.despine(left=True, bottom=True)
plt.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95)
plt.savefig(output_file)
Loading

0 comments on commit 78e652a

Please sign in to comment.