简体   繁体   English

如何使用 Pandas/Matplotlib 将 plot X 轴上的日期、Y 轴上的时间和 HH:MM 格式的当前时间作为刻度标签?

[英]How to plot Date in X Axis, Time in Y axis with Pandas/Matplotlib and present time in HH:MM format as tick labels?

I have date in one column and time in another which I retrieved from database through pandas read_sql.我在一列中有日期,在另一列中有时间,我通过 pandas read_sql 从数据库中检索到。 The dataframe looks like below (there are 30 -40 rows in my daaframe). dataframe 如下所示(我的 daaframe 中有 30 -40 行)。 I want to plot them in a time series graph.我想在时间序列图中对它们进行 plot 。 If I want I should be in a position to convert that to Histogram as well.如果我愿意,我也应该在 position 中将其转换为直方图。

    COB          CALV14
1  2019-10-04    07:04
2  2019-10-04    05:03
3  2019-10-03    16:03
4  2019-10-03    05:15

First I got different errors - like not numeric field to plot etc. After searching a lot,the closest post I could find is: Matplotlib date on y axis首先,我遇到了不同的错误——比如不是 plot 等的数字字段。经过大量搜索后,我能找到的最接近的帖子是: Matplotlib y 轴上的日期

I followed and got some result - However the problem is:我跟着并得到了一些结果-但是问题是:

I have to follow number of steps (convert to str then list and then to matplot lib datetime format) before I can plot them.在我可以 plot 之前,我必须遵循一些步骤(转换为 str 然后列表,然后转换为 matplot lib datetime 格式)。 (Please refer the code I am using) There must be a smarter and more precise way to do this. (请参考我正在使用的代码)必须有一种更智能、更精确的方法来做到这一点。 This does not show the time beside the axis the way they exactly appear in the data frame.这不会以它们在数据框中的确切显示方式显示轴旁边的时间。 (eg it should show 07:03, 05:04 etc) (例如,它应该显示 07:03、05:04 等)

New to python - will appreciate any help on this. python 的新手 - 将不胜感激任何帮助。

Code代码

ob_frame['COB'] = ob_frame.COB.astype(str)
ob_frame['CALV14'] = ob_frame.CALV14.astype(str)
date = ob_frame.COB.tolist()
time = ob_frame.CALV14.tolist()
y = mdates.datestr2num(date)
x = mdates.datestr2num(time)
fig, ax = plt.subplots(figsize=(9,9))
ax.plot(x, y)
ax.yaxis_date()
ax.xaxis_date()

fig.autofmt_xdate()
plt.show()

I found the answer to it.I did not need to convert the data retrieved from DB to string type.我找到了答案。我不需要将从数据库中检索到的数据转换为字符串类型。 Rest of the issue I was thought to be getting for not using the right formatting for the tick labels. Rest 我被认为是因为没有为刻度标签使用正确的格式而遇到的问题。 Here goes the complete code - Posting in case this will help anyone.这是完整的代码 - 发布以防万一这对任何人都有帮助。 In this code I have altered Y and X axis: i:e I plotted dates in x axis and time in Y axis as it looked better.在这段代码中,我改变了 Y 轴和 X 轴:我在 x 轴上绘制日期,在 Y 轴上绘制时间,因为它看起来更好。

###### Import all the libraries and modules needed ######
import IN_OUT_SQL as IS ## IN_OUT_SQL.py is the file where the SQL is stored
import cx_Oracle as co
import numpy as np
import Credential as cd # Credentia.py is the File Where you store the DB credentials
import pandas as pd
from  matplotlib import pyplot as plt
from matplotlib import dates as mdates
%matplotlib inline

###### Connect to DB, make the dataframe and prepare the x and y values to be plotted ######

def extract_data(query):
    '''
    This function takes the given query as input, Connects to the Databse, executes the SQL and 
    returns the result in a dataframe. 
    '''
    cred = cd.POLN_CONSTR #POLN_CONSTR in the credential file stores the credential in '''USERNAME/PASSWORD@DB_NAME''' format
    conn = co.connect(cred)
    frame = pd.read_sql(query, con = conn)
    return frame

query = IS.OUT_SQL
ob_frame = extract_data(query)
ob_frame.dropna(inplace = True) # Drop the rows with NaN values for all the columns
x = mdates.datestr2num(ob_frame['COB'])  #COB is date in "01-MAR-2020" format- convert it to madates type
y = mdates.datestr2num(ob_frame['CALV14']) #CALV14 is time in "21:04"  Format- convert it to madates type


###### Make the Timeseries plot of delivery time in y axis vs delivery date in x axis ######
fig, ax = plt.subplots(figsize=(15,8))
ax.clear() # Clear the axes
ax.plot(x, y, 'bo-', color = 'dodgerblue') #Plot the data
##Below two lines are to draw a horizontal line for 05 AM and 07 AM position
plt.axhline(y = mdates.date2num (pd.to_datetime('07:00')), color = 'red', linestyle = '--', linewidth = 0.75)
plt.axhline(y = mdates.date2num (pd.to_datetime('05:00')), color = 'green', linestyle = '--', linewidth = 0.75)
plt.xticks(x,rotation = '75')
ax.yaxis_date()
ax.xaxis_date()
#Below 6 lines are about setting the format with which I want my xor y ticks and their labels to be displayed
yfmt = mdates.DateFormatter('%H:%M') 
xfmt = mdates.DateFormatter('%d-%b-%y')
ax.yaxis.set_major_formatter(yfmt)
ax.xaxis.set_major_formatter(xfmt)
ax.yaxis.set_major_locator(mdates.HourLocator(interval=1))   # Every 1 Hour
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))   # Every 1 Day

####### Name the x,y labels, titles and beautify the plot #######
plt.style.use('bmh')
plt.xlabel('\nCOB Dates')
plt.ylabel('Time of Delivery (GMT/BST as applicable)\n')
plt.title(" Data readiness time against COBs (Last 3 months)\n")
plt.rcParams["font.size"] = "12" #Change the font 
# plt.rcParams["font.family"] = "Times New Roman" # Set the font type if needed
plt.tick_params(left = False, bottom = False, labelsize = 10) #Remove ticks, make tick labelsize 10
plt.box(False)

plt.show()

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何防止 matplotlib 图中的 y 轴刻度标签溢出? - How to prevent overrunning of y -axis tick labels in matplotlib plot? 如何在matplotlib中以'%H:%M'格式在y轴上绘制时间? - how to plot time on y-axis in '%H:%M' format in matplotlib? 如何在熊猫图中旋转 x 轴刻度标签 - How to rotate x-axis tick labels in a pandas plot 如何在X轴上相对于Y值绘制日期和时间(Python) - How to plot date and time in X axis against Y value (Python) Matplotlib:如何以时间(HH24:MI)为 Y 轴绘制图形 - Matplotlib: How to plot graph with time(HH24:MI) as Y-axis 在Matplotlib图中,x轴上有时间,如何使长轴和短轴标签不重叠? - In a Matplotlib plot with time on the x-axis, how to make the major and minor axis labels not overlap? 如何在 y 轴上一起绘制日期和时间 - How to plot date and time in the y axis together 如何在matplotlib中在x轴上显示日期和时间 - How to show date and time on x axis in matplotlib 将x轴刻度标签格式化为接缝,例如默认的熊猫图 - Format x-axis tick labels to seams like the default pandas plot 如何在 Matplotlib 中绘制一个非常大的数据集(日期、时间(x 轴)与每年每 15 分钟记录的值(y 轴)) - How to plot a very large data set (date,time (x axis) vs values recorded(y-axis) every 15 mins daily for a a year) in Matplotlib
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM