Home > Net >  How can I make the origin of the x-axis and the origin of the y-axis of a plot overlap in matplotlib
How can I make the origin of the x-axis and the origin of the y-axis of a plot overlap in matplotlib

Time:11-26

I have a simple graph to make, whose source code is below:

import pandas as pd

def plot_responses(index, y):
    index='Arsen initial'
    y=pd.Series({1: 0.8, 2: 0.8, 3: 0.59, 4: 0.54, 5: 0.86, 6: 0.54, 7: 0.97, 8: 0.69, 9: 1.39, 10: 0.95, 11: 2.12, 12: 1.95, 13: 0.99, 14: 0.76, 15: 0.82, 16: 0.63, 17: 1.09, 18: 0.9, 19: 1.0, 20: 0.84, 21: 0.71, 22: 0.71, 23: 0.59, 24: 0.58, 25: 1.66, 26: 1.48, 27: 1.71, 28: 1.69, 29: 1.98, 30: 1.22, 31: 1.09, 32: 1.41, 33: 1.11, 34: 0.83, 35: 4.11, 36: 4.81, 37: 5.28, 38: 4.87, 39: 4.66, 40: 5.1, 41: 0.61, 42: 0.58, 43: 0.74, 44: 0.43, 45: 0.69, 46: 0.43, 47: 0.62, 48: 0.2, 49: 0.77, 50: 0.93, 51: 0.56, 52: 0.77, 53: 0.91, 54: 0.55, 55: 1.15, 56: 0.53, 57: 0.62, 58: 0.42, 59: 0.55, 60: 0.41, 61: 0.67, 62: 0.5, 63: 0.72, 64: 0.53, 65: 0.77, 66: 0.68, 67: 0.65, 68: 0.42, 69: 0.59, 70: 0.3, 71: 0.8, 72: 0.54, 73: 0.61, 74: 0.77, 75: 0.8, 76: 0.37, 77: 1.21, 78: 0.73, 79: 0.81, 80: 0.8, 81: 0.45, 82: 0.43})
    values_for_5 = []
    values_for_30 = []
    for i in range(1, y.size   1):
    if i % 2 == 0:
        values_for_5.append(y[i])
    else:
        values_for_30.append(y[i])
    sample_no_for_5 = [i for i in range(1, len(y), 2)]
    sample_no_for_30 = [i   1 for i in range(1, len(y), 2)]
    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(1, 1, 1)
    ax.spines['left'].set_position('zero')
    ax.plot(sample_no_for_5, values_for_5, 'yo')
    ax.plot(sample_no_for_30, values_for_30, 'bo')
    plt.xlabel('Numarul mostrei', fontsize=15)
    plt.ylabel(index, fontsize=15)
    plt.title('Continutul de '   str(index.replace(' initial', ''))   ' din gudronul acid netratat')
    for i in range(len(values_for_30)):
        ax.text(sample_no_for_5[i], values_for_5[i], '5')
        ax.text(sample_no_for_30[i], values_for_30[i], '30')
    plt.xticks(range(0, y.size, 5))
    ax.grid()
    plt.savefig(str(index.replace('initial', '').strip())   '.jpg')
    plt.show()

Running this code, I get the following figure:

Initial picture

Which is pretty good, but I want two more things and I don't know how to do it:

  1. I want to make the origin of the y-axis overlap to the origin of the x-axis (the two zeros to have the same place);
  2. I want to get rid of the grid lines from the left of the y-axis

How do I do that?

CodePudding user response:

ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')

ax.set_xlim(0, y.size)
ax.set_ylim(0, max(y)   0.5)

this helps you to overlap both axises at (0,0) and gets rid of the lines that exceed the plot.

enter image description here

CodePudding user response:

Use this functions xlim() and ylim()

Link: https://pythonguides.com/matplotlib-set-axis-range/

  • Related