• Ask a Question
  • Create a Poll
150
    Ask a Question
    Cancel
    150
    More answer You can create 5 answer(s).
      Ask a Poll
      Cancel

      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?

      Asked by Jacobtimeffie on July 16, 2020 in Python.
      3 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

      Answered by Pasqualeroselindsey on July 16, 2020..

      I just flipped the other values and flip back the negative labels.

      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] group_b_values_neg = list(map(lambda n: n * -1, group_b_values))  max_value = max(group_a_values + group_b_values)  fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) ax2 = ax1.twiny() ax1.plot(group_a_names, group_a_values, c="blue") ax2.plot(group_b_names, group_b_values_neg, c="red")  ax1.set_ylim(max_value * -1, max_value) ax2.set_ylim(max_value * -1, max_value) ax2.set_yticklabels([str(abs(x)) for x in ax2.get_yticks()])  ax1.yaxis.set_ticks_position('both') ax1.tick_params(axis="y", labelright=True)  plt.show() 

      enter image description here

      Answered by Erasmovaleriajacklyn on July 16, 2020..

      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

      Answered by Aldenmarisophia on July 16, 2020..