Matplotlib:在给定字符串标签数组输入的情况下,设置手动xaxis标签,但仅限于主刻度

2024-04-19 08:57:46 发布

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

我试过了,但是标签打印位置不对。有些标签未打印,打印位置不正确。在

我有一个对应于每个数据点的标签数组。我只想打印一些标签,而且只打印在主要刻度上。但我不知道如何设置主要刻度,并使标签保持在正确的位置。在

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
fig, ax1 = plt.subplots(1, 1)
top = np.arange(100)
btm = top-2
x = np.arange(len(top))
ax1.vlines(x, top, btm, color='r', linewidth=1)

labels = np.linspace(200,300,100).astype(np.int).astype(np.str)
factor = 10
labels = [label for i,label in enumerate(labels) if ((i+1)%factor==1)]
plt.xticks(x, labels, rotation='horizontal')
from matplotlib.ticker import MultipleLocator, FormatStrFormatter, FixedFormatter
majorLocator   = MultipleLocator(factor)
majorFormatter = FixedFormatter(labels)
minorLocator   = MultipleLocator(1)
ax1.xaxis.set_minor_locator(minorLocator)
ax1.xaxis.set_major_formatter(majorFormatter)
ax1.xaxis.set_major_locator(majorLocator)
plt.tick_params(axis='both', which='major', labelsize=9, length=10)
plt.tick_params(axis='both', which='minor', labelsize=5, length=4)

救命啊。谢谢。在

编辑: 标签数组的长度与数据点的数量相同,等于x轴的长度。所以对于x轴位置的每一个增量,我都有相应的标签。所以对于x轴上的第i个位置或记号,应该有一个空标签,或者标签等于标签数组的第i个元素。如果它不应该是空的。标签不仅仅是整数,而是字符串。更具体地说,它们是日期时间字符串。在


Tags: 数据importlabelstopasnpplt标签
2条回答

enter image description here我需要的是带有FixedFormatter的FixedLocator,以及一个整数数组majorpos,它指定主要记号所在的索引。 另一个使用functformatter的答案会带来一些问题。在

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
fig, ax1 = plt.subplots(1, 1)
top = np.arange(100)
btm = top-2
x = np.arange(len(top))
ax1.vlines(x, top, btm, color='r', linewidth=1)

labels = np.linspace(200,300,100).astype(np.int).astype(np.str)
print(labels)
factor = 10
plt.xticks(x, labels, rotation='horizontal')

from matplotlib.ticker import MultipleLocator, FormatStrFormatter, FixedFormatter, FixedLocator
majorpos = np.arange(0,len(labels),int(len(labels)/10))
ax1.xaxis.set_major_locator(FixedLocator((majorpos)))
ax1.xaxis.set_major_formatter(FixedFormatter((labels[majorpos])))
ax1.xaxis.set_minor_locator(MultipleLocator(1))
plt.tick_params(axis='both', which='major', labelsize=9, length=10)
plt.tick_params(axis='both', which='minor', labelsize=5, length=4)

如果没有清晰的问题描述,我需要猜测以下可能是您想要的:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.ticker import MultipleLocator

fig, ax1 = plt.subplots(1, 1)
top = np.arange(100)
btm = top-2
x = np.arange(len(top))
ax1.vlines(x+200, top, btm, color='r', linewidth=1)

majorLocator   = MultipleLocator(10)
minorLocator   = MultipleLocator(1)
ax1.xaxis.set_major_locator(majorLocator)
ax1.xaxis.set_minor_locator(minorLocator)

plt.tick_params(axis='both', which='major', labelsize=9, length=10)
plt.tick_params(axis='both', which='minor', labelsize=5, length=4)

plt.show()

enter image description here

您也可以使用FuncFormatter作为ticklabels。在

^{pr2}$

相关问题 更多 >