2

我想以 24 小时间隔为辅助轴设置主要定位器,但它无效并且不会导致任何错误。

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

dt=pd.DataFrame({'time':[100000,200000,500000,800000],'value':[1,2,4,6]})
plot= plt.subplot()
plot.plot(dt.time,dt.value)
x_major_locator=plt.MultipleLocator(100000)
plot.xaxis.set_major_locator(x_major_locator)
plot.set_xlabel("Second")

s2h=lambda s: s/3600
h2s=lambda h: h*3600
ax2=plot.secondary_xaxis("top",functions=(s2h,h2s))
x_major_locator=plt.MultipleLocator(24)
ax2.xaxis.set_major_locator(x_major_locator)
ax2.set_xlabel("Hour")
plt.show()
4

1 回答 1

2

我不确定为什么不修改刻度;然而,解决这个问题的一种方法是创建一个新的子图轴,共享y. 只要您不更改限制,以下将起作用,因为这些线是相互绘制的。如果确实需要更改限制,那么您可以通过在负y空间中绘制线条并设置ylims将保留您的顶部 x 轴来做一个 hacky 方法。

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

dt=pd.DataFrame({'time':[100000,200000,500000,800000],'value':[1,2,4,6]})
plot= plt.subplot()
plot.plot(dt.time,dt.value)
x_major_locator=MultipleLocator(100000)
plot.xaxis.set_major_locator(x_major_locator)
plot.set_xlabel("Second")

s2h=lambda s: s/3600

h2s=lambda h: h*3600

#ax2=plot.secondary_xaxis("top",functions=(s2h,h2s))
ax2 = plot.twiny()
ax2.plot(s2h(dt.time),dt.value)



x_major_locator = MultipleLocator(24)
ax2.xaxis.set_major_locator(x_major_locator)
ax2.set_xlabel("Hour")

#ax2.set_xlim(0,200) #If you do this, you get 2 lines

plt.show()

在此处输入图像描述

于 2020-06-29T03:46:18.463 回答