Jack Hsueh
Jack Hsueh

Reputation: 125

How to set major locator of secondary axis

I want to set a major locator for a secondary axis with 24 hour intervals, but it’s not valid and does not result in any errors.

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()

Upvotes: 2

Views: 1962

Answers (1)

BenT
BenT

Reputation: 3200

I am not sure why the ticks are not being modified; however, one way to get around this is to create a new subplot axis that shares y. The following will work as long as you do not change the limits because the lines are plotted over each other. If do need to change the limits, then you can do a hacky approach by plotting the line in negative y space and setting the ylims which will preserve your top x-axis.

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()

enter image description here

Upvotes: 2

Related Questions