在python matplotlib上使用主要xtick时出现问题

2024-09-27 22:35:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在和我的朋友们讨论我的阴谋。 我的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()

结果是:

enter image description here

如您所见,标签仍然只打印在我的绘图的前面。 我希望它只会印在我的主要职位上。你知道吗


Tags: infromimportconfigasplt标签ax
1条回答
网友
1楼 · 发布于 2024-09-27 22:35:30

问题

如果我正确理解发生了什么,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只需根据字符串设置日期的格式(这里我选择格式hour,minute,second)。请注意,没有为次要记号设置格式设置程序,因此默认情况下matplotlib使用空格式设置程序(次要记号没有标签)。
这里是matplotlib的dates module文档。你知道吗

为了让您了解结果,这里是我使用上面的代码创建的一个图像,其中包含随机数据(只需查看x轴)。你知道吗

enter image description here

相关问题 更多 >

    热门问题