对于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()
and add_traces
Plot 1:一个图使用px.line()
该图显示了欧洲大陆人均国内生产总值最高的五个国家。数据使用如下参数进行分组color='country'
.
Plot 2:将数据添加到同一图
该图将美洲大陆人均国内生产总值最高的五个国家添加到第一个图。这就触发了以另一种方式识别数据的需要,以便能够看出数据是欧洲的还是美国的。这是使用参数处理的line_dash='country'
以便与原始图相比的所有新数据都有虚线。
这只是一种方法。如果最终结果是您想要的,我们也可以讨论其他方法。
完整代码:
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()