import plotly.express as px
import plotly.graph_objects as go
df = px.data.gapminder()
df = df.loc[df["country"].isin(
[
'Germany',
'United Kingdom',
'Finland',
'Belgium',
'Sweden',
'Denmark',
'Austria',
'Iceland',
'Netherlands',
'Switzerland',
'Ireland',
'Norway'
]
)
]
df["country_index"] = df.groupby("year")["country"].cumcount()
df = df.sort_values(["year", "GDPPercap"], ignore_index=True)
df["showlegend"] = df.groupby("country")["year"].cumcount() == 0
colors = px.colors.qualitative.Alphabet
fig = go.Figure()
for index, row in df.iterrows():
fig.add_trace(
go.Bar(
y=[row["year"]],
x=[row["pop"]],
customdata=[row["gdpPercap"]],
hovertemplate="%{x:2f}, GDP per capita: %{customdata:2f}",
marker=dict(color=colors[row["country_index"]]),
name=row["country"],
legendgroup=row["country"],
showlegend=row["showlegend"],
orientation="h"
)
)
fig.update_layout(barmode="stack", hovermode="y unified",template ='plotly_dark',width = 800,height = 800)
输出图形如下:
图1:
图2:
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved