简体   繁体   中英

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:

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):

在此处输入图片说明

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).

Simply:

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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