首页 > 解决方案 > 带有辅助 y 轴的 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()

图像如下所示:

在此处输入图像描述

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

在此处输入图像描述

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

标签: pythonmatplotlib

解决方案


简单地:

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

在此处输入图像描述


推荐阅读