The date is displayed incorrectly in matplotlib.

1 Description of this article

When I draw a time series graph using Python plot, date conversion does not work properly. For example, 2020-01-01 is mistakenly displayed as 0051-01-01.

80.JPG

2 Code where the date on the horizontal axis is displayed incorrectly

For the data frame generated by Pandas, display the graph with the command "Data frame.plot (...)" and use "mdates.DateFormatter ('% Y-% m-% d')" to "Format YMD". It turned out that the date is not displayed correctly when it is set to. When the code below is executed, the date on the horizontal axis is not displayed correctly.

/home/sampletest/sample.py


import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns

#Define a Data set.(The date is datetime.Describe in datetime. Notated by date type)
dat = [
    [datetime.datetime(2020,1,1),4,10],
    [datetime.datetime(2020,1,2),7,7],
    [datetime.datetime(2020,1,3),10,4],
    [datetime.datetime(2020,1,4),13,2],
    [datetime.datetime(2020,1,5),17,1],
    [datetime.datetime(2020,1,6),12,4],
    [datetime.datetime(2020,1,7),9,3],
    [datetime.datetime(2020,1,8),7,8],
    [datetime.datetime(2020,1,9),5,9],
    [datetime.datetime(2020,1,10),3,12],
    
    
]

dat=pd.DataFrame(dat,columns=["DATE","Y","Z"])
dat.set_index("DATE",inplace=True) #Set the date displayed on the horizontal axis to the index of DataFrame.
print(dat)


fig = sns.mpl.pyplot.figure() #Create an object to draw the graph.
ax=dat.plot(marker="o",figsize=(15, 5)) #Dataframe.An error occurs when drawing a graph in plot format
ax.legend() #Draw a legend

#Graph format settings(Set the date display method on the horizontal axis.)
days    = mdates.DayLocator(bymonthday=None, interval=2, tz=None)  #Horizontal axis: "Everyday" is displayed.(Without this line the date will be duplicated)
daysFmt = mdates.DateFormatter('%Y-%m-%d') #Horizontal axis: Format Y-M-Set to D.
ax.xaxis.set_major_locator(days) #Display the date on the horizontal axis.
ax.xaxis.set_major_formatter(daysFmt) #Display the date on the horizontal axis.
fig.autofmt_xdate() #The date on the horizontal axis is slanted so that it is easy to see.

#Give the graph a name
ax.set_xlabel('Date') #Set the X-axis title
ax.set_ylabel('Y') #Set the Y-axis title
plt.title(r"TEST",fontname="MS Gothic")  #Set the title of the graph. When specifying Japanese, it is necessary to specify fontname
#Set the size of the graph
fig.set_figheight(10)
fig.set_figwidth(20)
#Set the display range on the horizontal axis
ax.set_xlim(datetime.datetime(2020,1,1), datetime.datetime(2020,1,12)) 

3 Code that correctly displays the date on the horizontal axis

It is necessary to change the date line of the data frame from datetime to Matplotlib date.

Add dat ['DATE'] = mdates.date2num (dat ['DATE']).

/home/sampletest/sample.py


import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns
import pandas as pd

#Define a Data set.(The date is datetime.Describe in datetime. Notated by date type)
dat = [
    [datetime.datetime(2020,1,1),4,10],
    [datetime.datetime(2020,1,2),7,7],
    [datetime.datetime(2020,1,3),10,4],
    [datetime.datetime(2020,1,4),13,2],
    [datetime.datetime(2020,1,5),17,1],
    [datetime.datetime(2020,1,6),12,4],
    [datetime.datetime(2020,1,7),9,3],
    [datetime.datetime(2020,1,8),7,8],
    [datetime.datetime(2020,1,9),5,9],
    [datetime.datetime(2020,1,10),3,12],
     
]

dat=pd.DataFrame(dat,columns=["DATE","Y","Z"])
dat['DATE'] = mdates.date2num(dat['DATE'])  #Add here Convert datetime objects to Matplotlib dates.
dat.set_index("DATE",inplace=True) #Set the date displayed on the horizontal axis to the index of DataFrame.
print(dat)


fig = sns.mpl.pyplot.figure() #Create an object to draw the graph.
ax=dat.plot(marker="o",figsize=(15, 5))
ax.legend() #Draw a legend

#Graph format settings(Set the date display method on the horizontal axis.)
days    = mdates.DayLocator(bymonthday=None, interval=2, tz=None)  #Horizontal axis: "Everyday" is displayed.(Without this line the date will be duplicated)
daysFmt = mdates.DateFormatter('%Y-%m-%d') #Horizontal axis: Format Y-M-Set to D.
ax.xaxis.set_major_locator(days) #Display the date on the horizontal axis.
ax.xaxis.set_major_formatter(daysFmt) #Display the date on the horizontal axis.
fig.autofmt_xdate() #The date on the horizontal axis is slanted so that it is easy to see.

#Give the graph a name
ax.set_xlabel('Date') #Set the X-axis title
ax.set_ylabel('Y') #Set the Y-axis title
plt.title(r"TEST",fontname="MS Gothic")  #Set the title of the graph. When specifying Japanese, it is necessary to specify fontname
#Set the size of the graph
fig.set_figheight(10)
fig.set_figwidth(20)
#Set the display range on the horizontal axis
ax.set_xlim(datetime.datetime(2020,1,1), datetime.datetime(2020,1,12)) 
81.JPG

Recommended Posts

The date is displayed incorrectly in matplotlib.
Switch the language displayed in Django 1.9
The first step in Python Matplotlib
What to do if the image is not displayed using matplotlib etc. in the Docker container
[Python] The value written in Openpyxl is displayed in exponential notation (E).
Specify the color in the matplotlib 2D map
What is "mahjong" in the Python library? ??
When the target is Ubuntu 16.04 in Ansible
Is there NaN in the pandas DataFrame?
The date is displayed incorrectly in matplotlib.
PyQtGraph may not be available in the interpreter.
Even if the development language is changed to python3 in Cloud9, version 2 is displayed in python --version
Pipfile is not created in the current directory
What is wheezy in the Docker Python image?
About the difference between "==" and "is" in python
When the axis and label overlap in matplotlib
Put the second axis in 2dhistgram of matplotlib
What to do when only the window is displayed and nothing is displayed in pygame Note
Check if the string is a number in python
When the selected object in bpy.context.selected_objects is not returned
Linux is something like that in the first place
Omit the decimal point of the graph scale in matplotlib
What is the domain attribute written in Plotly's Layout?
Check if it is Unix in the scripting language
Set the form DateField to type = date in Django
[Tips] Save / copy the graph displayed in Jupyter Lab
Find the part that is 575 from Wikipedia in Python
Embedding in datetime when only the time is known
Check if it is Unix in the scripting language
When "ERROR: HTTP is not supported." Is displayed in mpsyt
Put matplotlib in Centos7.
Date manipulation in Python
View images in Matplotlib
The image is displayed in the local development environment, but the image is not displayed on the remote server of VPS
2D plot in matplotlib
Get date in Python
Date calculation in python
[Python] Split the date
Date calculation in Python
Test.py is not reflected on the web server in Python3.
What to do when Japanese is not displayed on matplotlib
[Pandas] If the first row data is in the header in DataFrame
Grayscale image is displayed as a color image in OpenCV / Python
Create SVG graph with matplotlib on heroku (displayed in Japanese)
Automatically get the port where Arduino is stuck in Python
Get the current date and time in Python, considering the time difference
Is there a bias in the numbers that appear in the Fibonacci numbers?
Find out how many each character is in the string.
When "No changes detected" is displayed in python3 manage.py makemigrations
In Django, how to abbreviate the long displayed string as ....
Change the message displayed when logging in to Raspberry Pi
Notes on coloring by value in the matplotlib scatter plot
Can't input Japanese in Flatpak application? The cause is Fcitx.