我想知道是否可以通过这种方式将xticks与xticklabels同步:
x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
XLabels = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U']
现在屏幕0 5 10 15 20,但在第二个子图上,有A B C D E.
我想看:A F K P U。
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, FormatStrFormatter, MultipleLocator # format X scale
import numpy as np
x=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot((np.arange(min(x), max(x)+1, 1.0)), 'b-')
ax2 = fig.add_subplot(2,1,2) # , sharex=ax1)
ax2.plot((np.arange(min(x), max(x)+1, 1.0)), 'r-')
#plt.setp(ax1.get_xticklabels(), visible=False)
ax2.xaxis.set_major_formatter(FormatStrFormatter('%0d'))
ax2.set_xticklabels(['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U'], fontsize=12)
plt.show()
如何同步,以便我有一个F K P U对应0 5 10 15 20?
答案 0 :(得分:0)
您可以过滤标签列表以获取与x轴匹配的标签,并使用set_xticks
和set_xticklabels
简化示例:
import matplotlib.pyplot as plt
x = [0, 5, 10, 15, 20]
labels = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U']
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(x, x, 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(x, x, 'r-')
ax2.set_xticks(x)
ax2.set_xticklabels([label for index, label in enumerate(labels) if index in x])
plt.show()
答案 1 :(得分:0)
最简单的选择是手动设置刻度线和刻度线标签。例如。如果你想勾选每个N
整数,你可以选择列表的一个子集([::N]
)来设置滴答和标签。
import matplotlib.pyplot as plt
import numpy as np
x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
XLabels = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q',
'R','S','T','U']
N = 5
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot((np.arange(min(x), max(x)+1, 1.0)), 'b-')
ax1.set_xticks(x[::N])
ax2 = fig.add_subplot(2,1,2) # , sharex=ax1)
ax2.plot((np.arange(min(x), max(x)+1, 1.0)), 'r-')
ax2.set_xticks(x[::N])
ax2.set_xticklabels(XLabels[::N], fontsize=12)
plt.show()
为了实现此功能的自动化,您可以使用FuncFormatter
,根据刻度线的位置从XLabels
列表中选择正确的字母。
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, FuncFormatter, MultipleLocator
import numpy as np
x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
XLabels = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q',
'R','S','T','U']
N = 5
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot((np.arange(min(x), max(x)+1, 1.0)), 'b-')
ax1.xaxis.set_major_locator(MultipleLocator(N))
ax2 = fig.add_subplot(2,1,2) # , sharex=ax1)
ax2.plot((np.arange(min(x), max(x)+1, 1.0)), 'r-')
def f(c,pos):
if int(c) in x:
d = dict(zip(x,XLabels))
return d[int(c)]
else:
return ""
ax2.xaxis.set_major_locator(MultipleLocator(N))
ax2.xaxis.set_major_formatter(FuncFormatter(f))
plt.show()