减少 plotly express 图表中的填充(顶部和底部)

Reduce padding (top and bottom) in plotly express chart

我有以下图表,但我想删除图表顶部和底部与第一个数据点之间的大 space。 (图片只是图表的一部分,因为我显示的是所有国家的数据,所以要大得多)

代码如下:

    fig = px.scatter(
    df, 
        x = 'happiness_score', 
        y = 'country',
        color = 'highlight',
        height=2500,
        hover_data = ['country', 'year', 'happiness_score'],
        color_discrete_map={'none': 'white'}
    )

    fig.update_yaxes(
        tickvals = df.country.unique(),              # make a line for each country
        
    )            

    fig.update_xaxes(
        tickwidth = 1,
        range = (1, 8.2)
    )

    fig.update_traces(
        marker = {
            'size': 12,
            'opacity':0.5,
            'line':{'width':1, 'color': 'DarkSlateGrey'}
        }
        
    )

    fig.update_layout({
        'plot_bgcolor': 'rgba(0, 0, 0, 0)'       # make the background transparent
        # 'paper_bgcolor': 'rgba(0, 0, 0, 0)'
    })

可能是 height 太大了,但如果我减小它,标签和数据点会重叠并使图表变得糟糕。如果我需要减少 height,如何在 y 轴的每个尖端之间添加 space?

顺便说一句,完整的代码在这里:https://github.com/GDevigili/happiness_data_vis/charts.py and the interface is on streamlit cloud https://share.streamlit.io/gdevigili/happiness_data_vis/main如果它有助于解决问题。

  • 定义y轴的范围
fig.update_yaxes(
    range=[-.5,len(df.country.unique())+.5],
    tickvals=df.country.unique(),  # make a line for each country
)

包括采购在内的完整代码

import plotly.express as px
import pandas as pd
import kaggle.cli
import sys, requests
from pathlib import Path
from zipfile import ZipFile
import urllib

# fmt: off
# download some images to demonstrate
url = "https://www.kaggle.com/unsdsn/world-happiness"
sys.argv = [sys.argv[0]] + f"datasets download {urllib.parse.urlparse(url).path[1:]}".split(" ")
kaggle.cli.main()

zfile = ZipFile(f'{urllib.parse.urlparse(url).path.split("/")[-1]}.zip')
dfs = {f.filename: pd.read_csv(zfile.open(f), on_bad_lines="skip", low_memory=False)for f in zfile.infolist()}

df = pd.concat([v.assign(year=k.split(".")[0]) for k,v in dfs.items()])
df = df.rename(columns={c:c.lower().replace(" ","_") for c in df.columns})
df["highlight"] = np.where(df["year"].astype(int)<2018, 'none', df["year"])
# fmt: on

fig = px.scatter(
    df,
    x="happiness_score",
    y="country",
    color="highlight",
    height=2500,
    hover_data=["country", "year", "happiness_score"],
    color_discrete_map={"none": "white"},
)

fig.update_yaxes(
    range=[-.5,len(df.country.unique())+.5],
    tickvals=df.country.unique(),  # make a line for each country
)

fig.update_xaxes(tickwidth=1, range=(1, 8.2))

fig.update_traces(
    marker={"size": 12, "opacity": 0.5, "line": {"width": 1, "color": "DarkSlateGrey"}}
)

fig.update_layout(
    {
        "plot_bgcolor": "rgba(0, 0, 0, 0)",  # make the background transparent
        # 'paper_bgcolor': 'rgba(0, 0, 0, 0)'
        "margin":{"l":0,"r":0,"t":0,"b":0}
    }
)