1

Goal: simple seaborn lineplot where the 24 hours of a day are on X axis, and their respective values on Y axis. X axis should start from 00:00:00 and end at 00:00:00.

Problem: while the graph is drawn fine, the X axis starts one hour too early and ends one hour too late (code below). See example:

enter image description here power is a Pandas dataframe where datetime is index (format is 2018-01-01 00:00:00) and Ap2 is a column with float64 values that I want to plot on a certain day.

def lineplotday(day, apartment):
    power_plot = power[day]

    fig, ax = plt.subplots(1, 1, figsize=(20, 10))

    sns.set(style="whitegrid")

    sns.lineplot(x=power_plot.index, y=apartment, data=power_plot)
    hours = mdates.HourLocator(interval=1)
    h_fmt = mdates.DateFormatter("%H:%M:%S")

    ax.xaxis.set_major_locator(hours)
    ax.xaxis.set_major_formatter(h_fmt)

    plt.tight_layout()

    fig.autofmt_xdate()

    plt.ylabel(str(apartment + " power draw on " + day))
    plt.savefig(str("powerplot_")+day+".png", dpi=300, facecolor="w")  

lineplotday("2018-08-21", "Ap2")

Above I define a function for plotting, and then call the function with the date and the column to plot.

I've tried adding xlim but don't know how it's supposed to work when the xticks (or what are they?) are datetime instead of, say, integers. Any ideas?

ps. feel free to comment if that plotting function looks stupid, I'm having a hard time understanding the proper use of seaborn/matplotlib...

KMFR
  • 895
  • 1
  • 15
  • 24
  • 3
  • You saved me again @ImportanceOfBeingErnest, thanks for your help. I tried googling and searching stackoverflow for hours and didn't find anything about .margins(), and everything pointed to that it should be done with xlim. Either the documentation on this stuff is super lacking or I'm just using wrong search terms... – KMFR Dec 12 '18 at 19:48
  • Hello, Add that as answer? :) – Arka Mallick Dec 12 '18 at 19:49
  • 1
    Of course you can also use `xlim`. But for that you need to know the date. Then you can convert this via `matplotlib.dates.date2num()` and use it inside `xlim`. It's definitely more complicated than adjusting the margins. – ImportanceOfBeingErnest Dec 12 '18 at 19:51

0 Answers0