简体   繁体   English

气泡大小图例 Python Plotly

[英]Bubble size legend with Python Plotly

I have created a bubble graph with Python Plotly. In the example below, the size of the bubble represents the size of the population for different countries.我用 Python Plotly 创建了一个气泡图。在下面的例子中,气泡的大小代表不同国家的人口数量。 I would like to add the bubble size in the legend like on the following picture:我想在图例中添加气泡大小,如下图所示:

在此处输入图像描述

But impossible, I really struggle to find a solution, either on Plotly documentation or on Forums like stack-overflow.但不可能,我真的很难找到解决方案,要么在 Plotly 文档上,要么在 stack-overflow 之类的论坛上。 Here is the code example:这是代码示例:

import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import math

# Load data, define hover text and bubble size
data = px.data.gapminder()
df_2007 = data[data['year']==2007]
df_2007 = df_2007.sort_values(['continent', 'country'])
df_2007 = df_2007[df_2007["continent"] == "Asia"]

hover_text = []
bubble_size = []

for index, row in df_2007.iterrows():
    hover_text.append(('Country: {country}<br>'+
                      'Life Expectancy: {lifeExp}<br>'+
                      'GDP per capita: {gdp}<br>'+
                      'Population: {pop}<br>'+
                      'Year: {year}').format(country=row['country'],
                                            lifeExp=row['lifeExp'],
                                            gdp=row['gdpPercap'],
                                            pop=row['pop'],
                                            year=row['year']))
    bubble_size.append(math.sqrt(row['pop']))

df_2007['text'] = hover_text
df_2007['size'] = bubble_size
sizeref = 2.*max(df_2007['size'])/(100**2)

# Dictionary with dataframes for each continent
continent_names = ['Asia']

continent_data = {continent:df_2007.query("continent == '%s'" %continent)
                              for continent in continent_names}

# Create figure
fig = go.Figure()

for continent_name, continent in continent_data.items():
    fig.add_trace(go.Scatter(
        x=continent['gdpPercap'], y=continent['lifeExp'],
        name=continent_name, text=continent['text'],
        marker_size=continent['size'],
        ))

# Tune marker appearance and layout
fig.update_traces(mode='markers', marker=dict(sizemode='area',
                                              sizeref=sizeref, line_width=2))

fig.update_layout(
    title='Life Expectancy v. Per Capita GDP, 2007',
    xaxis=dict(
        title='GDP per capita (2000 dollars)',
        gridcolor='white',
        type='log',
        gridwidth=2,
    ),
    yaxis=dict(
        title='Life Expectancy (years)',
        gridcolor='white',
        gridwidth=2,
    ),
    paper_bgcolor='rgb(243, 243, 243)',
    plot_bgcolor='rgb(243, 243, 243)',
)
fig.show()

Thanks for your help folks!感谢您的帮助!

  • clearly you can create a trace that is effectively the visualisation of a legend显然,您可以创建一条有效地可视化图例的轨迹
  • this trace can then be but against other axes and an overall figure can be created然后这条轨迹可以与其他轴相对,并且可以创建一个整体图形
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import math

# Load data, define hover text and bubble size
data = px.data.gapminder()
df_2007 = data[data["year"] == 2007]
df_2007 = df_2007.sort_values(["continent", "country"])
df_2007 = df_2007[df_2007["continent"] == "Asia"]
df_2007["pop_size"] = np.sqrt(df_2007["pop"])
fig1 = px.scatter(df_2007, x="gdpPercap", y="lifeExp", size="pop_size")

df_l = df_2007.sort_values("pop_size")
fig2 = px.scatter(
    df_l,
    x=np.zeros(len(df_2007)),
    y=pd.qcut(df_l["pop_size"], q=8, precision=0).astype(str),
    size="pop_size",
)


fig = go.Figure(
    data=[t for t in fig1.data] + [t.update(xaxis="x2", yaxis="y2") for t in fig2.data],
    layout=fig1.layout,
)

# now config axes appropriately
fig.update_layout(
    xaxis_domain=[0, 0.958],
    xaxis2={"domain": [0.96, 1], "matches": None, "visible": False},
    yaxis2={"anchor": "free", "overlaying": "y", "side": "right", "position": 1},
    showlegend=False,
)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM