0

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:

enter image description here

You can see that the line (in black color) does not follow the x-axis (see below):

enter image description here

How can I shift the line and make it follow the x-axis (i.e., the data points on the line should be pointing to the middle the of each x-label).

1 Answer 1

1

Simply:

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

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Or + width too... but glad to help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.