我进行了多次聊天,并添加了一条带有以下代码的y轴的直线:
import matplotlib.pyplot as plt
import numpy as np
labels = ['a','b','c','d','e']
d1 = [1, 1, 1, 1, 1]
d2 = [2, 2, 2, 2, 2]
d3 = [3, 3, 3, 3, 3]
d4 = [400, 600, 800, 1000, 1200]
x = np.arange(len(labels))
width = 0.25
fig, ax = plt.subplots()
rects1 = ax.bar(x + 0, d1, width, color='red')
rects2 = ax.bar(x + 0.25, d2, width, color='blue')
rects3 = ax.bar(x + 0.5, d3, width, color='green')
ax.set_xticks(x+0.25)
ax.set_xticklabels(labels)
ax2 = ax.twinx()
ax2.plot(d4, color='black', marker='*', linewidth=2, markersize=4)
ax2.margins(x=0.02)
plt.show()
图像如下所示:
您可以看到该线(黑色)不遵循x轴(见下文):
如何移动直线并使其沿x轴移动(即,直线上的数据点应指向每个x标签的中间)。