python x轴显示指定时间刻度

将x轴设置为时间轴
显示指定日期
注意事项:
在对x轴进行时间转换时需要注意:

  • datetime.date2num():是从1,1,1开始计数,单位是天
  • time.mktime():是从1970.1.1开始计数,单位是秒

实例

在这里插入图片描述

# 摘取自ww3项目Figure_area_average.py
import time, datetime, calendar
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as dt
import matplotlib.ticker as ticker
from matplotlib.dates import DateFormatter, MONDAY, MonthLocator, YearLocator
from Package_Read.Filter_tools import * #直接读取项目src包中的TXT文件
# 画图
fig = plt.figure(figsize=[9, 5])
ax = fig.add_subplot(1, 1, 1)

formatter = DateFormatter('%Y/%m/%d')
time1 = datetime.date(1970, 1, 1)
time2 = dt.date2num(time1)
timex0=timex
timex = timex/24/3600 + time2
ax.plot_date(timex[2:-1], dhf[2:-1], '-',label='high', alpha=1)
ax.plot_date(timex[2:-1], dbf[2:-1], '-',label='band', alpha=1)
ax.plot_date(timex[2:-1], dlf[2:-1], '-',label='low', alpha=1)
# ax.set_alpha = 0.8
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.grid(True) # 显示x刻度网格

# 设置x轴时间刻度
yeardays=YearLocator() # 获取每年第一日数据
mondays=MonthLocator() # 获取每月第一日数据
locate=MonthLocator(range(1, 13), bymonthday=1, interval=6) # 获取每6个月第一日数据

ax.xaxis.set_major_locator(locate) # 设定主刻度
ax.xaxis.set_minor_locator(mondays) # 设定次刻度
# autodates = dt.AutoDateLocator() # 自动显示x轴时间刻度
# ax.xaxis.set_major_locator(autodates) # 设置时间间隔
ax.xaxis.set_major_formatter(formatter) # 设置时间显示格式
fig.autofmt_xdate() # 自动旋转xlabel
# ax.yaxis.set_ticks_position('both') # 在图像左右两侧显示y轴刻度
formatter_y=ticker.PercentFormatter(xmax=100)
ax.yaxis.set_major_formatter(formatter_y)
ax.legend(loc='upper right', shadow=False)
# ax.set_xlabel('Time (year/month/day)')
ax.set_ylabel('$\int(U_{air}-U_{oc})/U_{oc}dt$')
ax.set_xlim(timex[0], timex[-1]) #设置时间轴
ax.set_title(f'Waves effect on surface current\n '
             f'lon:{lon1}-{lon2} lat:{lat1}-{lat2}')

fig.show()
fig.savefig(fig_file,dpi=300)
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,要将时间序列数据可视化并将x显示时间刻度,你可以使用pandas和matplotlib库。以下是一种方法: 首先,你需要确保你的时间列已经被解析为datetime格式。你可以使用pandas的to_datetime函数将日期列转换为datetime格式。例如,你可以使用以下代码读取CSV文件并解析日期列: ```python import pandas as pd train = pd.read_csv('demand-forecasting-kernels-only/train.csv', date_parser='date') train\['date'\] = pd.to_datetime(train\['date'\], format='%Y/%m/%d') ``` 接下来,你可以使用groupby函数对日期和店铺进行分组,并计算销售总额。然后,你可以使用sns.lineplot函数绘制线图,其中x为日期,y为销售额,hue参数可以用于区分不同的店铺。以下是示例代码: ```python import seaborn as sns sum_sale = train.groupby(\['date', 'store'\])\['sales'\].sum().reset_index() sns.lineplot(data=sum_sale, x='date', y='sales', hue='store') ``` 这样,你就可以将时间序列数据可视化,并且x显示时间刻度。希望这可以帮助到你!\[1\]\[2\] #### 引用[.reference_title] - *1* *2* [python sns 时间序列画图x刻度全黑](https://blog.csdn.net/weixin_43848469/article/details/112434831)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [python从csv读取数据用matplotlib绘制时间序列图,x时间间隔一个月显示](https://blog.csdn.net/weixin_39883129/article/details/111452475)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值