gpt4 book ai didi

python - 从 Plotly 中的 DataFrame 列添加多个文本标签

转载 作者:行者123 更新时间:2023-12-04 11:19:20 26 4
gpt4 key购买 nike

目标是使用 plotly 绘制一些数据其中文本参数包含多列。

这是我的数据帧:

import pandas as pd
import numpy as np
import plotly as py
import plotly.graph_objs as go

np.random.seed(1)
df = pd.DataFrame({'Mean Age': np.random.randint(40,60,10),
'Percent': np.random.randint(20,80,10),
'Number Column': np.random.randint(100,500,10)},
index=list('ABCDEFGHIJ'))

df.index.name = 'Text Column'
df = df.sort_values('Mean Age')

这是我如何使用一列中的文本绘制数据以在悬停时显示的示例:
# trace for Percent
trace0 = go.Scatter(
x = df.index,
y = df['Percent'],
name = 'Percent',
text = df['Mean Age'], # text to show on hover from df column
mode = 'lines+markers',
line = dict(
color = ('rgb(0,0,255)'), # blue
width = 4)
)

layout = dict(title = 'Test Plot',
xaxis = dict(title = 'Text Column'),
yaxis = dict(title = 'Percent'),
)

data = [trace0]
fig = dict(data=data, layout=layout)

py.offline.plot(fig, filename = 'Test_Plot.html')

我希望将另一列的数据添加到文本参数中。我可以通过做一些列表理解来实现这一点,但是有没有更简单/更有效的方法来做到这一点?

我正在寻找类似于下面的输出,但比使用列表理解更有效:
# column values to list
num = list(df['Number Column'])
age = list(df['Mean Age'])


# trace for Percent
trace0 = go.Scatter(
x = df.index,
y = df['Percent'],
name = 'Percent',
# list comprehension to get the data to show
text = [f'Number Column: {x}; Mean Age: {y}' for x,y in list(zip(num, age))],
mode = 'lines+markers',
line = dict(
color = ('rgb(0,0,255)'), # blue
width = 4)
)

layout = dict(title = 'Test Plot',
xaxis = dict(title = 'Text Column'),
yaxis = dict(title = 'Percent'),
)

data = [trace0]
fig = dict(data=data, layout=layout)

py.offline.plot(fig, filename = 'Test_Plot_Output.html')

最佳答案

您还可以按照以下方式做一些事情:

trace0 = go.Scatter(
x = df.index,
y = df['Percent'],
name = 'Percent',
# string concatenation in pandas
# also the <br> puts the data on a new line in the hover text
text = "Number Column: " + df["Number Column"].astype(str) + "<br>Mean Age: " + df["Mean Age"].astype(str),
mode = 'lines+markers',
line = dict(
color = ('rgb(0,0,255)'), # blue
width = 4)
)

关于python - 从 Plotly 中的 DataFrame 列添加多个文本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54368158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com