Plotly: How to annotate figure by a list of strings and a list of coordinates?

本小妞迷上赌 提交于 2020-05-28 06:57:45

问题


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?


回答1:


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

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!



来源:https://stackoverflow.com/questions/60975457/plotly-how-to-annotate-figure-by-a-list-of-strings-and-a-list-of-coordinates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!