Python 如何将样本的x位置与matplotlib.pyplot中的表列对齐?
我有一个包含一个图表和两个表格的图形 我希望将每个样本的x位置与相应列的中心对齐 列的数量与要打印的样本数量相同 我发现了这个,它涵盖了同样的问题,只是一个条形图 我无法将结果转移到我的案例中 下面是一个最小的工作代码示例:Python 如何将样本的x位置与matplotlib.pyplot中的表列对齐?,python,matplotlib,Python,Matplotlib,我有一个包含一个图表和两个表格的图形 我希望将每个样本的x位置与相应列的中心对齐 列的数量与要打印的样本数量相同 我发现了这个,它涵盖了同样的问题,只是一个条形图 我无法将结果转移到我的案例中 下面是一个最小的工作代码示例: import matplotlib.pyplot import numpy as np a = np.arange(20) b = np.random.randint(1, 5, 20) fig, ax = plt.subplots() ax.plot(a, b, ma
import matplotlib.pyplot
import numpy as np
a = np.arange(20)
b = np.random.randint(1, 5, 20)
fig, ax = plt.subplots()
ax.plot(a, b, marker='o')
ax.table(np.random.randint(1, 5, (4, 20)), loc="top")
ax.table(np.random.randint(1, 5, (4, 20)))
ax.set_xticklabels([])
plt.subplots_adjust(top=0.85, bottom=0.15)
fig.savefig('test.png')
它创建以下输出:
正如您所看到的,代表样本的圆没有朝向相应的列居中
感谢您的帮助 对我来说,更改
xlim
并因此对对齐进行硬编码总是有效的
plt.xlim(left=first-0.5, right=last+0.5)
将此集成到您的示例中将导致:
import matplotlib.pyplot
import numpy as np
a = np.arange(20)
b = np.random.randint(1, 5, 20)
fig, ax = plt.subplots()
ax.plot(a, b, marker='o')
ax.table(np.random.randint(1, 5, (4, 20)), loc="top")
ax.table(np.random.randint(1, 5, (4, 20)))
ax.set_xticklabels([])
plt.xlim(left=a[0]-0.5, right=a[-1]+0.5)
plt.subplots_adjust(top=0.85, bottom=0.15)
fig.savefig('test.png')
希望有帮助 这管用!因为我的原始数据在x轴上有datetime对象,所以我不得不添加/减去TimeDelta,但它还是成功了