How to draw line inside a scatter plot

前端 未结 2 1345
猫巷女王i
猫巷女王i 2020-12-29 00:13

I can\'t believe that this is so complicated but I tried and googled for a while now.

I just want to analyse my scatter plot with a few graphical features. For start

相关标签:
2条回答
  • 2020-12-29 00:36

    the p5 line should be:

    p5 = axScatter.plot([1,2,3],[1,2,3], "r--")
    

    argument 1 is a list of the x values, and argument 2 is a list of y values

    If you just want a straight line, you only need to provide values for the extremities of the line.

    0 讨论(0)
  • 2020-12-29 00:38

    plottakes either y values and uses x as index array 0..N-1 or x and y values as described in the documentation. So you could use

    p5 = axScatter.plot((0, 1), "r--")
    

    in your code to plot the line.

    However, you are asking for "good practice". The following code (hopefully) shows some "good practise" and some of the capabilities of matplotlib to create the plot you mention in your question.

    import numpy as np
    import matplotlib.pyplot as plt 
    
    # create some data
    xy = np.random.rand(4, 2)
    xy_line = (0, 1)
    
    # set up figure and ax
    fig, ax = plt.subplots(figsize=(8,8))
    
    # create the scatter plots
    ax.scatter(xy[:, 0], xy[:, 1], c='blue')
    for point, name in zip(xy, 'ABCD'):
        ax.annotate(name, xy=point, xytext=(0, -10), textcoords='offset points',
                    color='blue', ha='center', va='center')
    ax.scatter([0], [1], c='black', s=60)
    ax.annotate('Perfect Classification', xy=(0, 1), xytext=(0.1, 0.9),
                arrowprops=dict(arrowstyle='->'))
    
    # create the line
    ax.plot(xy_line, 'r--', label='Random guess')
    ax.annotate('Better', xy=(0.3, 0.3), xytext=(0.2, 0.4),
                arrowprops=dict(arrowstyle='<-'), ha='center', va='center')
    ax.annotate('Worse', xy=(0.3, 0.3), xytext=(0.4, 0.2),
                arrowprops=dict(arrowstyle='<-'), ha='center', va='center')
    # add labels, legend and make it nicer
    ax.set_xlabel('FPR or (1 - specificity)')
    ax.set_ylabel('TPR or sensitivity')
    ax.set_title('ROC Space')
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    ax.legend()
    plt.tight_layout()
    plt.savefig('scatter_line.png', dpi=80)
    

    scatter_with_line.png

    By the way: I think that matplotlibs documentation is quite useful nowadays.

    0 讨论(0)
提交回复
热议问题