简体   繁体   English

Python/matplolib:自动调整二级刻度标签(使用 %matplotlib notebook 的 jupyter notebook)

[英]Python/matplolib : auto-adjusting secondary tick labels (jupyter notebook using %matplotlib notebook)

I need help with the following issue: I am trying to plot some data using jupyter notebook in the matplotlib notebook mode.我需要有关以下问题的帮助:我正在尝试在 matplotlib 笔记本模式下使用 jupyter 笔记本 plot 一些数据。 The x-values are time data in seconds, y-values are numpy.float64. x 值是以秒为单位的时间数据,y 值为 numpy.float64。 I then convert the x-values to string values in the format hour:minutes:seconds.decimals.然后,我将 x 值转换为格式为小时:分钟:秒.小数的字符串值。

I want to plot my data in terms of the time in seconds and be able to add the string format of time under the first labels.我想 plot 我的数据以秒为单位,并且能够在第一个标签下添加时间的字符串格式。 Also I wish to zoom my plot (using the matplotlib notebook mode on jupyter notebook), as the first labels will automatically adjust to the new tick locations, I want the secondary (string format) labels to adjust as well.此外,我希望缩放我的 plot(在 jupyter 笔记本上使用 matplotlib 笔记本模式),因为第一个标签将自动调整到新的刻度位置,我希望辅助(字符串格式)标签也进行调整。

My data:我的数据:

%matplotlib notebook
import numpy as np
x = np.arange(32349, 32359, 1/10) # time format in seconds
y = np.cos(x)

This is how I convert the time format in the string format (h:min:s)这就是我将时间格式转换为字符串格式 (h:min:s) 的方式

import time
x_str = [] # time format in strings
for n in range(len(x)):
    decimals = str(round((x[n]-int(x[n])),3))[1:]
    x_str.append(time.strftime('%H:%M:%S', time.gmtime(x[n]))+decimals) # only way I could add the decimals

Does anyone have a solution for me?有人对我有解决方案吗? Thanks for your time.谢谢你的时间。

I seem to have find a solution using ticker.FuncFormatter:我似乎找到了使用ticker.FuncFormatter的解决方案:

from matplotlib import ticker

def secTo24h(x):
    decimals = str(round(x-int(x),3))[1:]
    xnew = time.strftime('%H:%M:%S', time.gmtime(x))+decimals
    return xnew

plt.figure(constrained_layout=True)
tick_to_24hourSys = lambda x,y: (secTo24h(x))
plt.plot(x, y)
ax = plt.gca()
myFormatter = ticker.FuncFormatter(tick_to_24hourSys)
ax.xaxis.set_major_formatter(myFormatter)
plt.setp(ax.get_xticklabels(), rotation=45)
plt.xlabel('time (24h)')
plt.ylabel('y')
plt.grid()
plt.show()

When zooming, the labels are automatically adjusting.缩放时,标签会自动调整。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM