By randomThought


2009-10-15 18:07:10 8 Comments

I have an array of timestamps in the format (HH:MM:SS.mmmmmm) and another array of floating point numbers, each corresponding to a value in the timestamp array.

Can I plot time on the x axis and the numbers on the y-axis using Matplotlib?

I was trying to, but somehow it was only accepting arrays of floats. How can I get it to plot the time? Do I have to modify the format in any way?

4 comments

@Kirk 2017-09-28 11:21:40

I had trouble with this using matplotlib version: 2.0.2. Running the example from above I got a centered stacked set of bubbles.

graph with centered stack of bubbles

I "fixed" the problem by adding another line:

plt.plot([],[])

The entire code snippet becomes:

import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


# make up some data
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot([],[])
plt.scatter(x,y)

# beautify the x-labels
plt.gcf().autofmt_xdate()
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)

plt.show()
plt.close()

This produces an image with the bubbles distributed as desired.

graph with bubbles distributed over time

@AimForClarity 2018-08-14 10:58:47

Doesnt work on py2.6 for me. I get ValueError: view limit minimum -0.05500000000000001 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units <Figure size 432x288 with 1 Axes>

@Qaswed 2020-03-04 12:31:25

A solution to the strange x-lims is to set them on your own: stackoverflow.com/questions/21423158/…

@GeorgeLPerkins 2017-07-13 21:05:01

7 years later and this code has helped me. However, my times still were not showing up correctly.

enter image description here

Using Matplotlib 2.0.0 and I had to add the following bit of code from Editing the date formatting of x-axis tick labels in matplotlib by Paul H.

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

I changed the format to (%H:%M) and the time displayed correctly. enter image description here

All thanks to the community.

@codeape 2009-10-15 18:18:26

You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format.

Plot the dates and values using plot_date:

dates = matplotlib.dates.date2num(list_of_datetimes)
matplotlib.pyplot.plot_date(dates, values)

@randomThought 2009-10-15 19:19:11

will it plot the Date or just the time? I only want the time since on conversion to datetime, the year is set to 1990.

@codeape 2009-10-19 13:53:50

"... on conversion to datetime, the year is set to 1990": Could you please post the code you use to convert from string to datetime? Something might be wrong with the conversion. Re. the formatting of chart labels, see the date_demo1 link provided by J. K. Seppänen. The matplot lib documentation is excellent, BTW. matplotlib.sourceforge.net/index.html

@Pete 2010-11-22 21:37:19

plot_dates --> matplotlib.pyplot.plot_date(dates,values)

@dwanderson 2016-10-05 16:23:43

What about a scatter plot? I want to provide a size array to determine the size of the scatter-bubbles, but there is no equivalent scatter_date(), and no obvious/direct way to get this graph.

@Arindam Roychowdhury 2017-07-20 06:59:10

The above returns a list with one object of type: matplotlib.lines.Line2D object. Now how do I use this to show the graph?

@moooeeeep 2013-05-07 20:30:05

You can also plot the timestamp, value pairs using pyplot.plot (after parsing them from their string representation). (Tested with matplotlib versions 1.2.0 and 1.3.1.)

Example:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

Resulting image:

Line Plot


Here's the same as a scatter plot:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.scatter(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

Produces an image similar to this:

Scatter Plot

@moooeeeep 2014-02-10 08:02:56

@andi it should work just as in my example (change plot to scatter).

@dwanderson 2016-10-05 16:21:33

I don't understand why this is the 5th question I've encountered where no one has actually TRIED using a scatter plot - it doesn't work. Type Error - invalid type promotion.

@moooeeeep 2016-10-06 07:26:50

@dwanderson Then, maybe you're doing something wrong. I've added an example for the scatter plot with datetime.datetime objects on the x axis to my post.

@Christophe Roussy 2016-11-30 09:16:57

For the grid add plt.grid(True)

@Akash Kandpal 2018-01-11 10:53:31

could you provide the data used?

@moooeeeep 2018-08-14 14:08:41

@AimForClarity Works for me with matplotlib.__version__ 2.2.2. The scatter plot has some overly wide x-limits set by default, though. This answer seems to provide a workaround other than manually adjusting plt.xlim(...): stackoverflow.com/a/46467896/1025391

@segFaultCoder 2019-05-21 18:44:30

plt.gcf().autofmt_xdate() is the ticket

@Qaswed 2020-03-04 12:29:57

@AkashKandpal, the data (x and y) are generated within the code. Without a seed being set, you cannot reproduce the graph to 100%, but you should be able to get the idea and to generate a similar graph.

Related Questions

Sponsored Content

26 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

44 Answered Questions

22 Answered Questions

[SOLVED] What are metaclasses in Python?

42 Answered Questions

[SOLVED] How to get the current time in Python

  • 2009-01-06 04:54:23
  • user46646
  • 3369263 View
  • 2970 Score
  • 42 Answer
  • Tags:   python datetime time

20 Answered Questions

[SOLVED] Save plot to image file instead of displaying it using Matplotlib

  • 2012-03-08 17:38:10
  • Homunculus Reticulli
  • 1678182 View
  • 1188 Score
  • 20 Answer
  • Tags:   python matplotlib plot

17 Answered Questions

[SOLVED] How do you change the size of figures drawn with matplotlib?

61 Answered Questions

[SOLVED] Calling an external command from Python

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

8 Answered Questions

[SOLVED] Hiding axis text in matplotlib plots

Sponsored Content