我正在使用 python 的 plotly 库创建一个基于线的时间序列图。我想将它连接到时间序列数据库,但目前我一直在使用 csv 数据进行测试。
是否可以有一个 x
和 y
轴(时间与值),并从另一个 csv 列值(主机)加载多行并附加到 x和 y 图?
import pandas as pd
import plotly.express as px
df = pd.read_csv('stats.csv')
fig = px.line(df, x = 'time', y = 'connections', title='connections')
fig.show()
我想在同一图表上用特定的 csv 主机列值定义多条线,以便每一线都由 host
列中的任何内容定义,并使用 time
与 connections
轴。 px.line
方法是否适用于该用例,还是我应该考虑另一种方法?
最佳答案
对于 plotly,您的源是数据库连接还是 csv 文件并不重要。无论哪种方式,您很可能会通过 pandas 数据框处理该部分。但是既然你在谈论数据库,我将向你展示如何在具有典型数据库结构的数据集上轻松构建绘图图表,在这种情况下你通常不得不依赖数据的分组和子集来显示变化随着时间的推移,您的数据的不同子类别。 Plotly Express 有一些有趣的数据集尝试 (dir(px.data)
),比如 gapminder 数据集:
country continent year lifeExp pop gdpPercap iso_alpha iso_num
0 Afghanistan Asia 1952 28.801 8425333 779.445314 AFG 4
1 Afghanistan Asia 1957 30.332 9240934 820.853030 AFG 4
2 Afghanistan Asia 1962 31.997 10267083 853.100710 AFG 4
3 Afghanistan Asia 1967 34.020 11537966 836.197138 AFG 4
4 Afghanistan Asia 1972 36.088 13079460 739.981106 AFG 4
如果您使用正确的方法,您可以轻松地使用 px.line()
在此类数据集上构建图形,并让图形函数为您处理分组。甚至可以使用相同的功能在以后向该图形添加数据。下图是使用 px.line()
、go.Figure()
和 add_traces
绘图 1: 使用 px.line()
此图显示了欧洲大陆人均国内生产总值最高的五个国家。数据使用 color='country'
等参数进行分组。
绘图 2: 将数据添加到同一图中
此图将美洲大陆人均国内生产总值最高的五个国家添加到第一个图中。这触发了以另一种方式辨别数据的需求,以便能够查看数据是欧洲的还是美国的。这是使用参数 line_dash='country'
处理的,因此与原始图相比的所有新数据都具有虚线。
Tihs 只是一种方法。如果最终结果符合您的要求,我们也可以讨论其他方法。
完整代码:
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
# Data
gapminder = px.data.gapminder()
# Most productive european countries (as of 2007)
df_eur = gapminder[gapminder['continent']=='Europe']
df_eur_2007 = df_eur[df_eur['year']==2007]
eur_gdp_top5=df_eur_2007.nlargest(5, 'gdpPercap')['country'].tolist()
df_eur_gdp_top5 = df_eur[df_eur['country'].isin(eur_gdp_top5)]
# Most productive countries on the american continent (as of 2007)
df_ame = gapminder[gapminder['continent']=='Americas']
df_ame_2007 = df_ame[df_ame['year']==2007]
df_ame_top5=df_ame_2007.nlargest(5, 'gdpPercap')['country'].tolist()
df_ame_gdp_top5 = df_ame[df_ame['country'].isin(df_ame_top5)]
# Plotly figure 1
fig = px.line(df_eur_gdp_top5, x='year', y='gdpPercap',
color="country",
line_group="country", hover_name="country")
fig.update_layout(title='Productivity, Europe' , showlegend=False)
# Plotly figure 2
fig2 = go.Figure(fig.add_traces(
data=px.line(df_ame_gdp_top5, x='year', y='gdpPercap',
color="country",
line_group="country", line_dash='country', hover_name="country")._data))
fig2.update_layout(title='Productivity, Europe and America', showlegend=False)
#fig.show()
fig2.show()
关于python - 如何在 plotly 时间序列图表中添加和定义多条线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59762321/