Untitled
import plotly.graph_objects as go import os import pandas as pd import numpy as np from matplotlib.colors import to_rgb # (Keep your existing color_list and asset_colors definitions) # Function to calculate contrast color (white or black) def get_contrast_color(hex_color): rgb = to_rgb(hex_color) brightness = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000 # Luminance formula return "black" if brightness > 0.5 else "white" # 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=i, x1=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=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=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=np.arange(len(df.index)) + 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=100, b=0), # Increased right margin for legend 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_folder = r"\\asiapac.nom\data\MUM\IWM\India_IWM_IPAS\Reet\Macro outlook Q4 2024\Macro Analysis 9 Jn" filename = "quilt_chart_plotly_hd_with_legend.png" full_path = os.path.join(save_folder, filename) fig.write_image(full_path, scale=4, width=2000, height=1200, engine="kaleido") # Save as high-resolution PNG fig.write_image(full_path, scale=8, engine="kaleido") # Show the chart fig.show()
Leave a Comment