Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: xticks every 15 minutes, starting on the hour

I am trying to plot values of temperature against time with the time formatted as HH:MM. I am able to set the xticks to recur every 15 minutes but the first tick is at the first time (e.g. 04:40).

Is there a way to shift the ticks to occur on the hour and on the concurrent quarter-hours (04:45, 05:00, 05:15, etc.)? My current code is as follows:

import matplotlib.pyplot as plt
import matplotlib.dates as md
import datetime as dt

## Dummy times and temperatures
time = [dt.datetime(2017,2,15,4,40),dt.datetime(2017,2,15,4,46),dt.datetime(2017,2,15,4,52),dt.datetime(2017,2,15,4,58),dt.datetime(2017,2,15,5,4),dt.datetime(2017,2,15,5,10)]
temp = [7, 8, 9, 10, 11, 12]

## Plot the data
figtemp, ax = plt.subplots(1, 1)
ax.plot(time, temp)

## Set time format and the interval of ticks (every 15 minutes)
xformatter = md.DateFormatter('%H:%M')
xlocator = md.MinuteLocator(interval = 15)

## Set xtick labels to appear every 15 minutes
ax.xaxis.set_major_locator(xlocator)

## Format xtick labels as HH:MM
plt.gcf().axes[0].xaxis.set_major_formatter(xformatter)
like image 794
user7606255 Avatar asked Feb 22 '17 17:02

user7606255


People also ask

How to get the current tick location of the x-axis in Matplotlib?

The matplotlib.pyplot.xticks () function is used to get or set the current tick locations and labels of the x-axis. It passes no arguments to return the current values without modifying them. Before we look into various implementations of Matplotlib xticks (), let me brief you with the syntax and return the same.

What is xticks in Matplotlib?

matplotlib.pyplot.xticks (ticks=None, labels=None, \*\*kwargs) ticks: array-like containing the list of xtick locations.

How to limit the number of ticks in Python Matplotlib?

To limit the number of ticks or control their frequency, some explicit actions must be taken Matplotlib is the defacto data visualization library for Python.

How to plot data in Python using matplotlib?

Plotting data in Python is easy when using Matplotlib. Plotted figures will often reflect automatically-determined axis markers (a.k.a. tick marks) based on values passed from datasets. To limit the number of ticks or control their frequency, some explicit actions must be taken Matplotlib is the defacto data visualization library for Python.


1 Answers

You could tell the MinuteLocator to only use the minutes 0,15,30,45 using the byminute argument.

xlocator = md.MinuteLocator(byminute=[0,15,30,45], interval = 1)
like image 77
ImportanceOfBeingErnest Avatar answered Nov 04 '22 16:11

ImportanceOfBeingErnest