python - 在 Matplotlib 中划分 x 和 y 标签

标签 python python-3.x matplotlib graph

我有一张图表,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

最佳答案

您可以将 matplotlib.ticker 中的 MultipleLocatorset_major_locatorset_minor_locator 一起使用。参见示例。

例子

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

结果

enter image description here

关于python - 在 Matplotlib 中划分 x 和 y 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48910859/

相关文章:

python - 字符串格式化参数的数量

python - 图像未显示在 Tkinter 窗口中

python-3.x - Python3中的CSV文件比较算法

python - 如何在不使用 with open 的情况下检查文件是否为空?

python - 更改 matplotlib 中的字体宽度

python - 使用matplotlib设置图例符号不透明度?

python - Turbogears 2 : authentication, 密码在不同表中,更新时反馈

python - 创建自定义日期范围,一天 22 小时 python

Python 变量和方程

python - matplotlib 3D 数据的 2D 切片