简体   繁体   English

Python Matplotlib 多条带辅助 y 轴

[英]Python Matplotlib multiple bar with secondary y-axis

I have a multiple bar chat and I added a line with a secondary y-axis with the following codes:我有一个多栏聊天,我添加了一条带有辅助 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()

The image is shown below:图像如下所示:

在此处输入图片说明

You can see that the line (in black color) does not follow the x-axis (see below):您可以看到该线(黑色)不跟随 x 轴(见下文):

在此处输入图片说明

How can I shift the line and make it follow the x-axis (ie, the data points on the line should be pointing to the middle the of each x-label).如何移动线并使其跟随 x 轴(即,线上的数据点应指向每个 x 标签的中间)。

Simply:简单地:

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM