在Matplotlib中划分x和y标签

问题描述 投票:3回答:1

我有一个图表,其中X作为日期,Y作为一些读数。 X轴的日期间隔增加一天。我想要的是在两天之间显示x轴上的小时数(只是为了设置图中黄色区域的小时数)。代码的想法是:

Date=[];Readings=[] # will be filled from another function
dateconv=np.vectorize(datetime.fromtimestamp)
Date_F=dateconv(Date)
ax1 = plt.subplot2grid((1,1), (0,0))
ax1.plot_date(Date_F,Readings,'-')
for label in ax1.xaxis.get_ticklabels():
    label.set_rotation(45)
ax1.grid(True)
plt.xlabel('Date')
plt.ylabel('Readings')
ax1.set_yticks(range(0,800,50))

plt.legend()
plt.show()

hours in yellow area

python python-3.x matplotlib graph
1个回答
1
投票

你可以使用MultipleLocatormatplotlib.tickerset_major_locator以及set_minor_locator。见例子。

Example

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import datetime

# Generate some data
d = datetime.timedelta(hours=1/5)
now =  datetime.datetime.now()
times = [now + d * j for j in range(250)]

ax = plt.gca() # get the current axes
ax.plot(times, range(len(times)))

for label in ax.xaxis.get_ticklabels():
    label.set_rotation(30)

# Set the positions of the major and minor ticks
dayLocator = MultipleLocator(1)
hourLocator = MultipleLocator(1/24)
ax.xaxis.set_major_locator(dayLocator)
ax.xaxis.set_minor_locator(hourLocator)

# Convert the labels to the Y-m-d format
xax = ax.get_xaxis() # get the x-axis
adf = xax.get_major_formatter() # the the auto-formatter
adf.scaled[1/24] = '%Y-%m-%d'  # set the < 1d scale to Y-m-d
adf.scaled[1.0] = '%Y-%m-%d' # set the > 1d < 1m scale to Y-m-d

plt.show()

Result

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.