Bar*_*rry 5 python annotations pandas plotly plotly-express
我想向我的线图添加许多带有箭头的注释。但是,我不想手动添加它们(就像我在下面的代码中所做的那样)。这将是一项艰巨的工作,我宁愿直接从 df['text'] 列(或本列中的列表)添加注释。
import plotly.express as px
import pandas as pd
# assign data of lists.
data = {'x': [0, 1, 2, 3, 4, 5, 6, 7, 8],
'y': [0, 1, 3, 2, 4, 3, 4, 6, 5],
'text':["","","Annotation1","","Annotation2","","","",""]}
# Create DataFrame
df = pd.DataFrame(data)
fig = px.line(df, x='x', y='y', title='I want to add annotation with the tekst column in my dataframe (instead of manually)')
fig.add_annotation(x=2, y=3,
text="Annotation1 (added manual)",
showarrow=True,
arrowhead= 2)
fig.add_annotation(x=4, y=4,
text="Annotation2 (added manual)",
showarrow=True,
arrowhead= 2)
fig.update_layout(showlegend=False)
fig.show()
Run Code Online (Sandbox Code Playgroud)
预期的结果如下所示(但我想用列表或类似的东西一次性添加注释):
非常感谢您的帮助。
我自己想出来了。请看下面的答案:
import plotly.express as px
import pandas as pd
# assign data of lists.
data = {'x': [0, 1, 2, 3, 4, 5, 6, 7, 8],
'y': [0, 1, 3, 2, 4, 3, 4, 6, 5],
'text':["","","Annotation1","","Annotation2","","","",""]}
# Create DataFrame
df = pd.DataFrame(data)
fig = px.line(df, x='x', y='y', title='I want to add annotation with the tekst column in my dataframe (instead of manually)')
arrow_list=[]
counter=0
for i in df['text'].tolist():
if i != "":
arrow=dict(x=df['x'].values[counter],y=df['y'].values[counter],xref="x",yref="y",text=i,arrowhead = 2,
arrowwidth=1.5,
arrowcolor='rgb(255,51,0)',)
arrow_list.append(arrow)
counter+=1
else:
counter+=1
fig.update_layout(annotations=arrow_list)
fig.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3308 次 |
| 最近记录: |