Untitled

 avatar
unknown
plain_text
a month ago
2.7 kB
1
Indexable
# Add a thin whitespace between the last two years and the others
whitespace_gap = 0.2
year_positions = np.arange(len(df.index))
year_positions[-2:] += whitespace_gap  # Add gap for the last two years

# Create the quilt chart
fig = go.Figure()

# Loop through years and assets
for i, year in enumerate(df.index):
    ranked_assets = df.loc[year].sort_values(ascending=True)
    for j, (asset, value) in enumerate(ranked_assets.items()):
        color = asset_colors[asset]
        asset_name = asset[:10]  # Abbreviated name if needed
        text_color = get_contrast_color(color)  # Dynamic text color

        # Add a rectangle for each asset
        fig.add_shape(
            type="rect",
            x0=year_positions[i],
            x1=year_positions[i] + 1,
            y0=j,
            y1=j + 1,
            fillcolor=color,
            line=dict(color="white"),
        )

        # Add text annotations for asset name and value
        fig.add_annotation(
            x=year_positions[i] + 0.5,
            y=j + 0.7,
            text=asset_name,
            showarrow=False,
            font=dict(size=9, color=text_color, family="Arial Black")
        )
        fig.add_annotation(
            x=year_positions[i] + 0.5,
            y=j + 0.3,
            text=f"{value:.2f}%",
            showarrow=False,
            font=dict(size=11, color=text_color, family="Arial Black")
        )

    # Add traces for legend (only once per asset)
    if i == 0:
        for asset in df.columns:
            fig.add_trace(
                go.Scatter(
                    x=[None],
                    y=[None],
                    mode="markers",
                    marker=dict(size=8, color=asset_colors[asset]),
                    name=asset,
                    legendgroup=asset,
                    showlegend=False
                )
            )

# Adjust x-axis
fig.update_xaxes(
    tickvals=year_positions + 0.5,
    ticktext=df.index,
    tickfont=dict(size=16, color="black"),
    side="top",
    showgrid=False,
    zeroline=False,
)

# Adjust y-axis
fig.update_yaxes(showgrid=False, zeroline=False, visible=False)

# Set aspect ratio and layout
fig.update_layout(
    width=1100,  # Increased width to accommodate legend
    height=700,
    margin=dict(l=0, r=100, t=0, b=0),  # Removed top margin for title space
    plot_bgcolor="white",
    legend=dict(
        yanchor="top",
        y=1,
        xanchor="left",
        x=1.02,
        bgcolor="rgba(255,255,255,0.8)",
        bordercolor="Black",
        borderwidth=1
    )
)

# Save as high-resolution PNG
fig.write_image(full_path, scale=6, width=2000, height=1200, engine="kaleido")  # Reduced scale for better text clarity

# Show the chart
fig.show()
Leave a Comment