带有辅助y轴的Python Matplotlib多栏

时间:2020-09-24 20:19:37

标签: python matplotlib

我进行了多次聊天,并添加了一条带有以下代码的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()

图像如下所示:

enter image description here

您可以看到该线(黑色)不遵循x轴(见下文):

enter image description here

如何移动直线并使其沿x轴移动(即,直线上的数据点应指向每个x标签的中间)。

1 个答案:

答案 0 :(得分:1)

简单地:

ax2.plot(x+0.25, d4, color='black', marker='*', linewidth=2, markersize=4)

enter image description here