Reputation: 3747
Still pretty new to data visulization and trying to do a simple graph to monitor my weight lose attempt. Matplotlib though seems to be doing something weird when plotting the dates and not sure how to specify for the graph to use my dates instead of trying to always start at the start of the month
import pandas as pd
import numpy as np
dfOrg = pd.DataFrame({"Date": ["2019-1-7", "2019-1-14", "2019-1-21","2019-1-28","2019-2-4","2019-2-11",
"2019-2-18", "2019-2-25", "2019-3-4"],
"Weight:": [204.3,201,202.5,200.7,201.5,202.5,199.5,200.8,201.5]})
dfOrg["Date"] = pd.to_datetime(dfOrg['Date'])
maxDT = dfOrg["Date"].max()
missing = {}
missing["Date"] = pd.date_range(start=maxDT, end='2019-10-07', freq='7D',closed="right")
missing["Weight"] = []
for i in missing["Date"]:
missing["Weight"].append(np.NaN)
missingDF = pd.DataFrame(missing)
df = pd.concat([dfOrg, missingDF], ignore_index=True)
df.drop(["Weight"], axis=1, inplace=True)
df.rename(columns={"Weight:": "Weight"}, inplace=True)
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import datetime
formatter = dates.DateFormatter('%b %d')
plt.plot(df["Date"], df["Weight"], color="g")
plt.xticks(rotation=70)
plt.ylabel("LBS")
plt.title("Weight Loss Progress")
plt.axhline(linewidth=4, color='gold', y=170, label="Goal")
plt.ylim(160, 210)
plt.legend(bbox_to_anchor=[1, 0.5], loc='center left')
plt.gcf().axes[0].xaxis.set_major_formatter(formatter)
plt.show()
So ideally the graph should be showing my weight where the dates go from 2019-1-7 to 2019-10-07 which is my goal and a goal line. Instead when I see the graph it shows
Upvotes: 1
Views: 40
Reputation: 248
You can use
plt.xlim([plt.xlim()[0], datetime.date(2019, 10, 7)])
to adjust the x-axis range. This will give you
Edit - You can set the ticks to one per week on a specified weekday using
plt.gca().xaxis.set_major_locator(dates.WeekdayLocator(byweekday=dates.MO))
Upvotes: 1