matplotlib, how to compress parts of x axis

前端 未结 1 1219
再見小時候
再見小時候 2020-12-21 22:29

Hey guys this is my first time posting here and hopefully this question isn\'t too trivial. I tried looking for a solution to this but couldn\'t find what I wanted.

相关标签:
1条回答
  • 2020-12-21 22:52

    This should do it:

    from matplotlib import pyplot as plt
    
    fig,ax = plt.subplots()
    
    x = [1,2,3,10,11]
    y = [1,2,3,4,5]
    
    ax.plot(y,marker='o')
    ax.set_xticks([i for i in range(len(y))])
    ax.set_xticklabels(x)
    plt.show()
    

    I added the markers to visualise the data points better. The result looks like this:

    EDIT:

    If you want to visualise that the axis is not continuous, you can find help in this answer.

    EDIT2:

    In my example, I only passed the y-values to the plot function, which means that the x-values are implicitly calculated to be [1,2,3,4,5]. You can of course also pass the x-values for each plot command explicitly and thereby variate at which x-value which plot starts. For the example in your comment, this would be:

    fig,ax = plt.subplots()
    
    y1 = [1,2,3,4,5]
    x1 = [i for i in range(len(y1))]
    y2 = [2,3,4,5,6]
    x2 = [i+1 for i in range(len(y2))]
    
    xticks = list(set(x1+x2)) #or more explicit: [i for i in range(6)]
    xtick_labels = [1,2,3,10,11,12]
    
    ax.plot(x1,y1,marker='o')
    ax.plot(x2,y2,marker='x')
    ax.set_xticks(xticks)
    ax.set_xticklabels(xtick_labels)
    plt.show()
    
    0 讨论(0)
提交回复
热议问题