Matplotlib scatter plot with different text at each data point

后端 未结 9 2077
挽巷
挽巷 2020-11-22 12:50

I am trying to make a scatter plot and annotate data points with different numbers from a list. So, for example, I want to plot y vs x and annotate

相关标签:
9条回答
  • 2020-11-22 13:32

    I'm not aware of any plotting method which takes arrays or lists but you could use annotate() while iterating over the values in n.

    y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
    z = [0.15, 0.3, 0.45, 0.6, 0.75]
    n = [58, 651, 393, 203, 123]
    
    fig, ax = plt.subplots()
    ax.scatter(z, y)
    
    for i, txt in enumerate(n):
        ax.annotate(txt, (z[i], y[i]))
    

    There are a lot of formatting options for annotate(), see the matplotlib website:

    enter image description here

    0 讨论(0)
  • 2020-11-22 13:36

    For limited set of values matplotlib is fine. But when you have lots of values the tooltip starts to overlap over other data points. But with limited space you can't ignore the values. Hence it's better to zoom out or zoom in.

    Using plotly

    import plotly.express as px
    df = px.data.tips()
    
    df = px.data.gapminder().query("year==2007 and continent=='Americas'")
    
    
    fig = px.scatter(df, x="gdpPercap", y="lifeExp", text="country", log_x=True, size_max=100, color="lifeExp")
    fig.update_traces(textposition='top center')
    fig.update_layout(title_text='Life Expectency', title_x=0.5)
    fig.show()
    

    0 讨论(0)
  • 2020-11-22 13:38

    I would love to add that you can even use arrows /text boxes to annotate the labels. Here is what I mean:

    import random
    import matplotlib.pyplot as plt
    
    
    y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
    z = [0.15, 0.3, 0.45, 0.6, 0.75]
    n = [58, 651, 393, 203, 123]
    
    fig, ax = plt.subplots()
    ax.scatter(z, y)
    
    ax.annotate(n[0], (z[0], y[0]), xytext=(z[0]+0.05, y[0]+0.3), 
        arrowprops=dict(facecolor='red', shrink=0.05))
    
    ax.annotate(n[1], (z[1], y[1]), xytext=(z[1]-0.05, y[1]-0.3), 
        arrowprops = dict(  arrowstyle="->",
                            connectionstyle="angle3,angleA=0,angleB=-90"))
    
    ax.annotate(n[2], (z[2], y[2]), xytext=(z[2]-0.05, y[2]-0.3), 
        arrowprops = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1))
    
    ax.annotate(n[3], (z[3], y[3]), xytext=(z[3]+0.05, y[3]-0.2), 
        arrowprops = dict(arrowstyle="fancy"))
    
    ax.annotate(n[4], (z[4], y[4]), xytext=(z[4]-0.1, y[4]-0.2),
        bbox=dict(boxstyle="round", alpha=0.1), 
        arrowprops = dict(arrowstyle="simple"))
    
    plt.show()
    

    Which will generate the following graph:

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