Formatting X axis with dates format Matplotlib

佐手、 提交于 2021-02-19 08:35:08

问题


I have written code which plots the past seven day stock value for a user-determined stock market over time. The problem I have is that I want to format the x axis in a YYMMDD format. I also don't understand what 2.014041e7 means at the end of the x axis.

Values for x are:

20140421.0, 20140417.0, 20140416.0, 20140415.0, 20140414.0, 20140411.0, 20140410.0

Values for y are:

531.17, 524.94, 519.01, 517.96, 521.68, 519.61, 523.48

My code is as follows:

mini = min(y)
maxi = max(y)
minimum = mini - 75
maximum = maxi + 75
mini2 = int(min(x))
maxi2 = int(max(x))

plt.close('all')
fig, ax = plt.subplots(1)
pylab.ylim([minimum,maximum])
pylab.xlim([mini2,maxi2])

ax.plot(x, y)
ax.plot(x, y,'ro')
ax.plot(x, m*x + c)
ax.grid()
ax.plot()

回答1:


When plotting your data using your method you are simply plotting your y data against numbers (floats) in x such as 20140421.0 (which I assume you wish to mean the date 21/04/2014).

You need to convert your data from these floats into an appropriate format for matplotlib to understand. The code below takes your two lists (x, y) and converts them.

import numpy as np

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

import datetime as dt

# Original data

raw_x = [20140421.0, 20140417.0, 20140416.0, 20140415.0, 20140414.0, 20140411.0, 20140410.0]
y = [531.17, 524.94, 519.01, 517.96, 521.68, 519.61, 523.48]

# Convert your x-data into an appropriate format.

# date_fmt is a string giving the correct format for your data. In this case
# we are using 'YYYYMMDD.0' as your dates are actually floats.
date_fmt = '%Y%m%d.0'

# Use a list comprehension to convert your dates into datetime objects.
# In the list comp. strptime is used to convert from a string to a datetime
# object.
dt_x = [dt.datetime.strptime(str(i), date_fmt) for i in raw_x]

# Finally we convert the datetime objects into the format used by matplotlib
# in plotting using matplotlib.dates.date2num
x = [mdates.date2num(i) for i in dt_x]

# Now to actually plot your data.
fig, ax = plt.subplots()

# Use plot_date rather than plot when dealing with time data.
ax.plot_date(x, y, 'bo-')

# Create a DateFormatter object which will format your tick labels properly.
# As given in your question I have chosen "YYMMDD"
date_formatter = mdates.DateFormatter('%y%m%d')

# Set the major tick formatter to use your date formatter.
ax.xaxis.set_major_formatter(date_formatter)

# This simply rotates the x-axis tick labels slightly so they fit nicely.
fig.autofmt_xdate()

plt.show()

The code is commented throughout so should be easily self explanatory. Details on the various modules can be found below:

  1. datetime
  2. matplotlib.dates

Example



来源:https://stackoverflow.com/questions/23219218/formatting-x-axis-with-dates-format-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!