我的情节中有我的xticks。 我的x向量上有hh:mm:ss格式数据,但是xticks标签只是占用了我的x向量上的空间。 我正在尝试仅使用主要的xticks,它们会在5分钟的时间内显示x向量标签。
但是,标签显示不正确。
现在这是我编写的代码:
# -*- coding: utf-8 -*-
from os import listdir
from os.path import isfile, join
import pandas as pd
from Common import common as comm
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
fp = FontProperties(fname="../templates/fonts/msgothic.ttc")
config = comm.configRead()
commonConf = comm.getCommonConfig(config)
peopleBhvConf = comm.getPeopleBhvConf(config)
files = [f for f in listdir(commonConf['resultFilePath']) if isfile(join(commonConf['resultFilePath'], f))]
waitTimeGraphInput = [s for s in files if peopleBhvConf['resultFileName'] in s]
waitTimeGraphFile = commonConf['inputFilePath'] + waitTimeGraphInput[0]
waitTimeGraph = pd.read_csv(waitTimeGraphFile)
# Create data
N = len(waitTimeGraph.index)
x = waitTimeGraph['ホール入時間']
y = waitTimeGraph['滞留時間(出-入sec)']
xTicks = pd.date_range(min(x), max(x), freq="5min")
fig, ax = plt.subplots()
ax.scatter(x, y)
ax.set_xticklabels(xTicks, rotation='vertical')
plt.axhline(y=100, xmin=min(x), xmax=max(x), linewidth=2, color = 'red')
plt.setp(ax.get_xticklabels(), visible=True, rotation=30, ha='right')
plt.savefig(commonConf['resultFilePath'] + '1人1人の待ち時間分布.png')
plt.show()
这是结果:
如您所见,标签仍然只打印在我绘图的前面。 我希望它只会在我的主要xticks职位上打印。
答案 0 :(得分:1)
如果我正确理解发生了什么,则xTicks
数组比x
短,对吗?如果是这样,那就是问题所在。
我在您的代码中看不到您设置刻度位置的位置,但是我想您正在显示所有这些位置,x
的每个元素一个。但是,由于您使用ax.set_xticklabels(xTicks, rotation='vertical')
手动设置了刻度线标签,因此matplotlib无法知道这些标签应移至哪个刻度线,因此它将填充第一个可用的刻度线,并且如果还有更多的刻度线,它们将没有标签。
如果您能够阅读标签,您会发现书面日期与轴上标记的位置不符。
一般规则是,确保手动设置刻度标签时,包含标签的数组的长度与刻度数组的长度相同。在不需要标签的刻度线中添加空字符串。
但是,由于您谈到过major ticks and minor ticks,因此,我向您展示了如何设置x轴上有日期的情况。
不需要丢弃xTicks
。不要手动设置刻度标签,因此不要使用ax.set_xticklabels()
。
您的代码应为:
fig, ax = plt.subplots()
ax.scatter(x, y)
plt.axhline(y=100, xmin=min(x), xmax=max(x), linewidth=2, color = 'red')
ax.xaxis.set_major_locator(MinuteLocator(interval=5))
ax.xaxis.set_minor_locator(MinuteLocator(interval=1))
ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))
plt.setp(ax.get_xticklabels(), visible=True, rotation=30, ha='right')
plt.savefig(commonConf['resultFilePath'] + '1人1人の待ち時間分布.png')
记住要导入定位器和格式化程序:
from matplotlib.dates import MinuteLocator, DateFormatter
简要说明:MinuteLocator
在x轴上找到每分钟的间隔并打勾。参数interval
允许您每N分钟设置一个刻度。因此,在上面的代码中,每5分钟放置一个大刻度,每分钟放置一个小刻度。
DateFormatter
只需将日期格式相应地设置为字符串即可(这里我选择小时,分钟,秒的格式)。请注意,尚未为次要刻度设置任何格式化程序,因此默认情况下,matplotlib使用空格式化程序(次要刻度没有标签)。
这里是matplotlib的dates module上的文档。
为使您对结果有所了解,这是我使用上面的代码创建的带有随机数据的图像(只看x轴)。