How to set the xticklabels for date in matplotlib

2024/9/28 13:26:00

I am trying to plot values from two list. The x axis values are date. Tried these things so far

year = [20070102,20070806,20091208,20111109,20120816,20140117,20140813]
yvalues = [-0.5,-0.5,-0.75,-0.75,-0.5,-1.25,-1.25]dates = [datetime.datetime.strptime(str(int(date)),'%Y%m%d') for date in year]fig, axes = plt.subplots(1, 1, figsize=(16, 9), dpi=100)line1, = axes.plot(dates,yvalues, lw=2, marker='*', color='r')
axes.legend([line1],['VALUES'],loc=1)
axes.grid()
axes.set_xlabel('YEAR')
axes.set_ylabel('VALUES')yticks = [-2.0,-1.75,-1.5,-1.25,-1.0,-0.75,-0.5,-0.25,0.0]
axes.set_yticks(yticks)
axes.set_yticklabels(["$%.2f$" % y for y in yticks]);axes.set_xticks(dates)
#axes.set_xticklabels()

The figure seems good. But unable to label the x axis ticks correctly. I am trying to label x axis with something like 2007-01-02 or 2007 Jan.

Thanks in advance

Answer

You can control the format of the dates using a DateFormater:

import matplotlib.dates as mdates
xfmt = mdates.DateFormatter('%Y-%m-%d')
axes.xaxis.set_major_formatter(xfmt)

import datetime as DT
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdatesyear = [20070102,20070806,20091208,20111109,20120816,20140117,20140813]
yvalues = [-0.5,-0.5,-0.75,-0.75,-0.5,-1.25,-1.25]dates = [DT.datetime.strptime(str(int(date)),'%Y%m%d') for date in year]fig, axes = plt.subplots(1, 1, figsize=(16, 9), dpi=100)line1, = axes.plot(dates,yvalues, lw=2, marker='*', color='r')
axes.legend([line1],['VALUES'],loc=1)
axes.grid()
axes.set_xlabel('YEAR')
axes.set_ylabel('VALUES')yticks = [-2.0,-1.75,-1.5,-1.25,-1.0,-0.75,-0.5,-0.25,0.0]
axes.set_yticks(yticks)
axes.set_yticklabels(["$%.2f$" % y for y in yticks]);xfmt = mdates.DateFormatter('%Y-%m-%d')
axes.xaxis.set_major_formatter(xfmt)
axes.set_xticks(dates)
plt.xticks(rotation=25)
plt.show()

yields

enter image description here

https://en.xdnf.cn/q/71335.html

Related Q&A

PyParsing: Is this correct use of setParseAction()?

I have strings like this:"MSE 2110, 3030, 4102"I would like to output:[("MSE", 2110), ("MSE", 3030), ("MSE", 4102)]This is my way of going about it, although I h…

Indent and comments in function in Python

I am using Python 2.7 and wrote the following:def arithmetic(A):x=1 """ Some comments here """ if x=1:x=1elif x=2:x=2return 0But it has the indentation issue:if x=1:^ Ind…

Read a large big-endian binary file

I have a very large big-endian binary file. I know how many numbers in this file. I found a solution how to read big-endian file using struct and it works perfect if file is small:data = []file = open(…

SWIG Python Structure Array

Ive been searching for a few days trying to figure out how to turn an array of structures into a Python list. I have a function that returns a pointer to the beginning of the array.struct foo {int memb…

Hashing tuple in Python causing different results in different systems

I was practicing tuple hashing. In there I was working on Python 2.7. Below is the code:num = int(raw_input()) num_list = [int(x) for x in raw_input().split()] print(hash(tuple(num_list)))The above cod…

ctypes pointer into the middle of a numpy array

I know how to get a ctypes pointer to the beginning of a numpy array:a = np.arange(10000, dtype=np.double) p = a.ctypes.data_as(POINTER(c_double)) p.contents c_double(0.0)however, I need to pass the po…

Extracting unsigned char from array of numpy.uint8

I have code to extract a numeric value from a python sequence, and it works well in most cases, but not for a numpy array.When I try to extract an unsigned char, I do the followingunsigned char val = b…

How to hold keys down with pynput?

Im using pynput and I would like to be able to hold keys down, specifically wasd but when I try and run this code it only presses the key and doesnt hold it for 2 seconds. If anyone knows what Im doing…

How well does your language support unicode in practice?

Im looking into new languages, kind of craving for one where I no longer need to worry about charset problems amongst inordinate amounts of other niggles I have with PHP for a new project.I tend to fin…

analogy to scipy.interpolate.griddata?

I want to interpolate a given 3D point cloud:I had a look at scipy.interpolate.griddata and the result is exactly what I need, but as I understand, I need to input "griddata" which means some…