繁体   English   中英

如何使plot的x轴原点和y轴原点在matplotlib中重叠?

[英]How can I make the origin of the x-axis and the origin of the y-axis of a plot overlap in matplotlib?

我有一个简单的图表,其源代码如下:

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

运行这段代码,我得到下图:

初始图片

这很好,但我还想要两件事,但我不知道该怎么做:

  1. 我想让y轴的原点与x轴的原点重叠(两个零点在同一位置);
  2. 我想摆脱 y 轴左侧的网格线

我怎么做?

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)

这有助于您在 (0,0) 处重叠两个轴并去除超过 plot 的线。

在此处输入图像描述

使用此函数xlim()ylim()

链接: https://pythonguides.com/matplotlib-set-axis-range/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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