-2

I have data that looks like below. The Date/Time field is in %m-%d-%Y %H:%M:%S format.

           Date/Time  Utilization
 04-01-2020 10:00:00           10
 04-01-2020 10:10:00           20
 04-01-2020 10:20:00           50
 04-01-2020 10:30:00           10
 04-02-2020 15:30:00           20
 04-02-2020 15:40:00           10
 04-02-2020 15:50:00           10
 04-07-2020 23:40:00           40
 04-07-2020 23:50:00           50

I want to plot this in Matplotlib, with x-axis as the date/time and y-axis as the utilization.

When I plot this, each of these 10 minute intervals are all squished together in the X-Axis (screenshot below): enter image description here

My code for above is this:

def plot_graph(utilization_map):
    utilization_array = []
    date_array = []
    for each_time in utilization_map:
        utilization = utilization_map[each_time]
        utilization_array.append(utilization)
        human_time = convert_epoch_to_datetime_for_plots(each_time) # This converts the epoch time in %m-%d-%Y %H:%M:%S format
        date_array.append(human_time)
    x_axis = date_array
    y_axis = utilization_array
    plt.plot(x_axis, y_axis, color='b')
    plt.title("Utilization")
    plt.xlabel("Days")
    plt.ylabel("Percent of Utilization")
    plt.legend()
    plt.show()

Question: I want to plot it in a way that the X-axis labels show only in %m-%d or %m-%d-%Y format and with daily intervals instead of 10 minutes, so all the times are not mushed together in the X-axis. How do I do this?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
BlueChips23
  • 1,861
  • 5
  • 34
  • 53
  • https://matplotlib.org/3.1.1/gallery/recipes/common_date_problems.html – wwii Apr 08 '20 at 17:02
  • Related: [Changing the formatting of a datetime axis in matplotlib](https://stackoverflow.com/questions/43968985/changing-the-formatting-of-a-datetime-axis-in-matplotlib) ... [Format of datetime in pyplot axis](https://stackoverflow.com/questions/29968654/format-of-datetime-in-pyplot-axis) ... Many more searching with variants of `python matplotlib x axis date format site:stackoverflow.com` – wwii Apr 08 '20 at 17:10
  • The code provided is your function, but this is not reproducible code, in that you haven't included everything required to run the code. – Trenton McKinney Apr 08 '20 at 17:21

1 Answers1

0
  • Use pandas.DataFrame.resample to combine the data from 10 minutes to daily and then plot it.
    • pd.DataFrame(df['util'].resample('D').sum())

imports

import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
import numpy as np

create reproducible dataframe

dates = pd.date_range(start='2014-04-01', end='2020-04-07', freq='10min').tolist()

np.random.seed(0) 
utilization = [np.random.randint(10, 50) for _ in range(len(dates))]


df = pd.DataFrame({'dates': dates, 'util': utilization})
df.set_index('dates', inplace=True)


                     util
dates                    
2014-04-01 00:00:00    26
2014-04-01 00:10:00    44
2014-04-01 00:20:00    36
2014-04-01 00:30:00    13
2014-04-01 00:40:00    41
2014-04-01 00:50:00    30
2014-04-01 01:00:00    21
2014-04-01 01:10:00    10
2014-04-01 01:20:00    25
2014-04-01 01:30:00    18

resample dataframe to daily

df_daily = pd.DataFrame(df['util'].resample('D').sum())

            util
dates           
2014-04-01  4096
2014-04-02  4338
2014-04-03  4194
2014-04-04  4186
2014-04-05  4262
2014-04-06  4342
2014-04-07  4101
2014-04-08  4445
2014-04-09  4346
2014-04-10  4378

plot the dataframe

fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111)
ax.plot(df_daily.index, df_daily['util'])
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.show()

enter image description here

  • This data is random from numpy so all the average sums are about 4200, for this example.
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158