Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib twin y axis

I want to plot my data with 0 at the middle of y axis. Just like this:
enter image description here

This is what I came up with:
enter image description here

Using this code:

import matplotlib.pyplot as plt

group_a_names = ['A', 'B', 'C', 'D', 'E']
group_a_values = [2, 4, 6, 8, 10]

group_b_names = ['F', 'G', 'H', 'I', 'J']
group_b_values = [1, 2, 3, 4, 5]

fig, ax1 = plt.subplots(figsize=(5, 4), dpi=100)
ax2 = ax1.twiny()

ax1.plot(group_a_names, group_a_values)
ax2.plot(group_b_names, group_b_values)

plt.show()

How can I visualize my data just like the first image? Also mirror the y tick labels/marks on the right side?

like image 530
conquistador Avatar asked Jun 28 '26 04:06

conquistador


2 Answers

Try this:

import matplotlib.pyplot as plt
group_a_names = ['A', 'B', 'C', 'D', 'E']
group_a_values = [2, 4, 6, 8, 10]

group_b_names = ['F', 'G', 'H', 'I', 'J']
group_b_values = [-2, -4, -6, -8, -10]

fig, ax1 = plt.subplots(figsize=(5, 4), dpi=100)
ax1.plot(group_a_names, group_a_values)

# add second x axis
ax3 = ax1.twiny()
ax3.plot(group_b_names, group_b_values)

# add second y axis
ax2 = ax1.twinx()

# set y axis range
plt.ylim(-10, 10)

plt.show()

Result:

enter image description here

like image 150
TobiWestside Avatar answered Jun 30 '26 17:06

TobiWestside


This worked for me:

ticks = np.arange(2, 11, 2)
plt.yticks(ticks, [10, 5, 0, 5, 10])

ax1.yaxis.set_ticks_position('both')
ax1.tick_params(axis="y", labelright=True)

enter image description here

like image 41
Mateo Lara Avatar answered Jun 30 '26 16:06

Mateo Lara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!