Search code examples
pythonplotly

How to annotate figure by a list of strings and a list of coordinates


I am plotting a certain list, Z[i, j] of length D, using matplotlib along with the annotation of the points taken from another list, index_word_map[i], as follows:

plt.scatter(Z[:,0], Z[:,1])
for i in range(D):
    plt.annotate(s=index_word_map[i], xy=(Z[i,0], Z[i,1]))
plt.show()

Now, I want to do the same using plotly or plotly express. I can plot the points using plotly express as follows:

X = []
Y = []
for i in range(D):
    x = Z[i,0]
    y = Z[i,1]
    X.append(x)
    Y.append(y)
fig = px.scatter(x=X, y=Y)

But, how am I to use the annotation list (index_word_map[i]) to have the labels of the points to show up on the plot also?


Solution

  • If I understand correctly, you'd like to achieve something like this:

    enter image description here

    What you're looking at here is a list D of some plotly color themes used as annotations for a scatter plot of x and y values organized as a list of lists Z.

    D=['Alphabet','Antique','Bold','D3','Dark2','Dark24','G10','Light24','Pastel','Pastel1']
    
    Z=[[0, 0],[1, 2],[2, 4],[3, 6],[4, 8],[5, 10],[6, 12],[7, 14],[8, 16],[9, 18]]
    

    Complete code:

    import numpy as np
    import plotly.express as px
    import plotly.graph_objs as go
    
    # sample data
    D=['Alphabet','Antique','Bold','D3','Dark2','Dark24','G10','Light24','Pastel','Pastel1']
    
    # sample of two lists
    z1 =np.arange(len(D)).tolist()
    z2 = [i*2 for i in z1]
    
    # turn two lists into a list of tuples
    # containing each element of z1 of z2
    # as zipped pairs
    tuplist = list(zip(z1, z2))
    
    # turn the list of tuples into list of lists
    Z=[list(elem) for elem in tuplist]
    
    
    # plotly setup
    fig = go.Figure(data=go.Scatter(x=z1, y=z2, marker_color='black'))
    
    for i, m in enumerate(D):
        fig.add_annotation(dict(font=dict(color='rgba(0,0,200,0.8)',size=12),
                                            x=Z[i][0],
                                            y=Z[i][1],
                                            showarrow=False,
                                            text=D[i],
                                            textangle=0,
                                            xanchor='left',
                                            xref="x",
                                            yref="y"))
    fig.show()
    

    I hope this is what you were looking for. Don't hesitate to let me know if not!