in python
- User
in python
Assistant
Here's how to create tables with log-scaled color mapping in Python using pandas and various styling options:
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LogNorm, Normalize import seaborn as sns # Create sample data with wide range of values np.random.seed(42) data = pd.DataFrame({ 'category': list('ABCDEFGH'), 'value_linear': [1, 5, 10, 20, 50, 100, 150, 200], 'value_skewed': [0.1, 1, 10, 100, 1000, 10000, 100000, 1000000] # Log-scaled values }) # Function to apply log-scaled color mapping def color_scale_log(s, cmap='viridis', na_color='white', vmin=None, vmax=None): """ Apply a logarithmic color scale to a pandas Series. Parameters: ----------- s : pandas.Series The data to color cmap : str or matplotlib colormap The colormap to use na_color : str Color for NaN values vmin, vmax : float, optional Min and max values for color scaling Returns: -------- list of CSS background-color specifications """ # Handle zeros for log scale (replace with small value) s_for_log = s.copy() s_for_log = s_for_log.replace(0, 0.01) # Replace zeros with small value # Get min/max values if vmin is None: vmin = s_for_log.min() if vmax is None: vmax = s_for_log.max() # Create a logarithmic normalization norm = LogNorm(vmin=vmin, vmax=vmax) # Get colormap if isinstance(cmap, str): cmap = plt.cm.get_cmap(cmap) # Apply colors colors = [f'background-color: {plt.colors.rgb2hex(cmap(norm(x)))}' if pd.notnull(x) else f'background-color: {na_color}' for x in s_for_log] return colors # 1. Using pandas styling with log scale styled_table = data.style.apply( lambda x: color_scale_log(x, cmap='viridis'), subset=['value_skewed'] ).apply( lambda x: ['background-color: #{:02x}{:02x}{:02x}'.format( *plt.cm.viridis(plt.Normalize()(x.astype(float)))[:3].astype(int) * 255) for v in x], subset=['value_linear'] ).format({ 'value_linear': '{:,.1f}', 'value_skewed': '{:,.1f}' }) # Display the styled table styled_tableFor more control and additional options, you can use libraries like Plotly:
import plotly.graph_objects as go import plotly.express as px import numpy as np # Create a table with log-scaled colors using Plotly fig = go.Figure(data=[go.Table( header=dict( values=list(data.columns), fill_color='paleturquoise', align='left' ), cells=dict( values=[data[col] for col in data.columns], fill_color=[ ['white'] * len(data), # No color for category column px.colors.sample_colorscale('Blues', [x/200 for x in data['value_linear']]), # Linear scale px.colors.sample_colorscale('Viridis', [np.log10(x)/6 for x in data['value_skewed']]) # Log scale ], align='left', format=[None, '.1f', '.1f'] )) ]) fig.update_layout( title='Table with Linear vs Log Color Scales', width=700 ) fig.show()For a more interactive dashboard-style table, you can use Dash with DataTable:
from dash import Dash, dash_table import dash_bootstrap_components as dbc import numpy as np # Function to generate color scale based on log values def generate_log_color_scale(values, colorscale='viridis'): import plotly.colors # Handle zeros by replacing with small value values = [max(0.01, v) for v in values] # Convert to log scale normalized between 0-1 log_values = np.log10(values) min_val, max_val = min(log_values), max(log_values) normalized = [(v - min_val) / (max_val - min_val) for v in log_values] # Sample colors from the colorscale colors = plotly.colors.sample_colorscale(colorscale, normalized) return colors # Create style data conditional for the table linear_colors = px.colors.sample_colorscale('Blues', [x/200 for x in data['value_linear']]) log_colors = generate_log_color_scale(data['value_skewed']) style_data_conditional = [] # Add style for each cell in value_linear column for i, color in enumerate(linear_colors): style_data_conditional.append({ 'if': {'row_index': i, 'column_id': 'value_linear'}, 'backgroundColor': color, 'color': 'white' if i > len(linear_colors)/2 else 'black' }) # Add style for each cell in value_skewed column for i, color in enumerate(log_colors): style_data_conditional.append({ 'if': {'row_index': i, 'column_id': 'value_skewed'}, 'backgroundColor': color, 'color': 'white' if i > len(log_colors)/2 else 'black' }) # Create the Dash app (this would be run in a Dash application) app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.layout = dash_table.DataTable( id='table', columns=[{"name": i, "id": i} for i in data.columns], data=data.to_dict('records'), style_data_conditional=style_data_conditional, style_header={ 'backgroundColor': 'rgb(230, 230, 230)', 'fontWeight': 'bold' } ) # For demonstration, you would run this with app.run_server()For a simpler approach using just pandas and matplotlib, you can also use:
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LogNorm # Create a function for log-scaled heatmap tables def log_scale_heatmap_table(df, log_columns=None, cmap='viridis', figsize=(10, 6)): """ Create a table visualization with log-scaled color mapping for specified columns Parameters: ----------- df : pandas DataFrame The data to visualize log_columns : list Columns to apply log scaling to cmap : str Matplotlib colormap name figsize : tuple Figure size """ if log_columns is None: log_columns = [] # Create a figure and axis fig, ax = plt.subplots(figsize=figsize) ax.axis('tight') ax.axis('off') # Create the table table = ax.table( cellText=df.values, colLabels=df.columns, loc='center', cellLoc='center' ) # Style the table table.auto_set_font_size(False) table.set_fontsize(10) table.scale(1.2, 1.5) # Apply colors to specified columns for col_idx, col in enumerate(df.columns): if col in log_columns: # Get column values values = df[col].values # Handle zeros for log scale values_for_log = np.copy(values) values_for_log[values_for_log <= 0] = np.min(values_for_log[values_for_log > 0]) / 10 # Create log norm norm = LogNorm(vmin=np.min(values_for_log), vmax=np.max(values_for_log)) cmap_obj = plt.cm.get_cmap(cmap) # Apply colors to cells for row_idx in range(len(df)): cell = table[(row_idx+1, col_idx)] # +1 for header row val = values_for_log[row_idx] color = cmap_obj(norm(val)) cell.set_facecolor(color) # Set text color based on background brightness brightness = 0.299 * color[0] + 0.587 * color[1] + 0.114 * color[2] text_color = 'white' if brightness < 0.5 else 'black' cell.get_text().set_color(text_color) plt.tight_layout() return fig # Use the function fig = log_scale_heatmap_table(data, log_columns=['value_skewed'], cmap='viridis') plt.show()Would you like me to explain or break down any part of these code examples?
- User
polars df, gt.GT(pldf)
Assistant
Here's how to create a table with log-scaled color mapping using Polars and gt.GT:
import polars as pl import numpy as np from gt import GT import matplotlib.pyplot as plt from matplotlib.colors import LogNorm # Create sample data with wide range of values data = { 'category': list('ABCDEFGH'), 'value_linear': [1, 5, 10, 20, 50, 100, 150, 200], 'value_skewed': [0.1, 1, 10, 100, 1000, 10000, 100000, 1000000] # Log-scaled values } # Create a Polars DataFrame pldf = pl.DataFrame(data) # Function to create CSS styles for log-scaled colors def log_scale_colors(values, cmap='viridis', min_val=None, max_val=None): """Generate CSS background-color styles using log scale""" # Handle zeros and negative values for log scale values_for_log = np.array(values) if min_val is None: min_val = np.min(values_for_log[values_for_log > 0]) if max_val is None: max_val = np.max(values_for_log) # Replace zeros/negatives with a small value for log scaling values_for_log = np.maximum(values_for_log, min_val / 10) # Create log normalization norm = LogNorm(vmin=min_val, vmax=max_val) # Get colormap cmap_obj = plt.cm.get_cmap(cmap) # Generate CSS styles styles = [] for val in values_for_log: color = cmap_obj(norm(val)) hex_color = plt.colors.rgb2hex(color) # Determine text color based on background brightness brightness = 0.299 * color[0] + 0.587 * color[1] + 0.114 * color[2] text_color = 'white' if brightness < 0.5 else 'black' styles.append({ 'background-color': hex_color, 'color': text_color }) return styles # Create the GT table from Polars DataFrame table = GT(pldf) # Format the numeric columns table.fmt_number( columns=['value_linear', 'value_skewed'], decimals=1, use_seps=True ) # Add title and subtitle table.tab_header( title="Log-Scaled Color Mapping Example", subtitle="Comparing linear and logarithmic color scales" ) # Apply linear color scale to value_linear column linear_values = pldf['value_linear'].to_list() linear_min = min(linear_values) linear_max = max(linear_values) linear_norm = plt.Normalize(vmin=linear_min, vmax=linear_max) linear_cmap = plt.cm.get_cmap('Blues') for i, val in enumerate(linear_values): color = linear_cmap(linear_norm(val)) hex_color = plt.colors.rgb2hex(color) brightness = 0.299 * color[0] + 0.587 * color[1] + 0.114 * color[2] text_color = 'white' if brightness < 0.5 else 'black' table.tab_style( style=[ ('background-color', hex_color), ('color', text_color) ], locations=['cells'], rows=i+1, # +1 because GT uses 1-based indexing for rows columns='value_linear' ) # Apply log color scale to value_skewed column log_styles = log_scale_colors(pldf['value_skewed'].to_list(), cmap='viridis') for i, style in enumerate(log_styles): table.tab_style( style=[ ('background-color', style['background-color']), ('color', style['color']) ], locations=['cells'], rows=i+1, # +1 because GT uses 1-based indexing for rows columns='value_skewed' ) # Add footnote explaining the color scales table.tab_footnote( footnote="value_linear uses a linear color scale; value_skewed uses a logarithmic color scale" ) # Display the table tableFor a more streamlined approach that better integrates with gt's data_color functionality (if available in your version of gt), you can use this alternative:
import polars as pl import numpy as np from gt import GT import matplotlib.pyplot as plt from matplotlib.colors import LogNorm # Create sample data data = { 'category': list('ABCDEFGH'), 'value_linear': [1, 5, 10, 20, 50, 100, 150, 200], 'value_skewed': [0.1, 1, 10, 100, 1000, 10000, 100000, 1000000] } # Create a Polars DataFrame pldf = pl.DataFrame(data) # Create the GT table table = GT(pldf) # Format numeric columns table.fmt_number( columns=['value_linear', 'value_skewed'], decimals=1, use_seps=True ) # Add title table.tab_header( title="Log-Scaled Color Mapping in Tables", subtitle="Using gt with Polars DataFrame" ) # Define a custom color palette function for log scale def log_color_mapper(x, palette='viridis', domain=None): """Map values to colors using a logarithmic scale""" if domain is None: domain = (min(x), max(x)) # Handle zeros and negative values x_for_log = np.maximum(np.array(x), domain[0]/10 if domain[0] > 0 else 0.01) # Create log normalization norm = LogNorm(vmin=max(0.01, domain[0]), vmax=domain[1]) # Get colormap cmap = plt.cm.get_cmap(palette) # Map values to colors colors = [plt.colors.rgb2hex(cmap(norm(val))) for val in x_for_log] return colors # Apply linear color scale to value_linear column linear_values = pldf['value_linear'].to_list() linear_domain = (min(linear_values), max(linear_values)) linear_colors = plt.cm.Blues(plt.Normalize()(linear_values)) linear_hex_colors = [plt.colors.rgb2hex(color) for color in linear_colors] for i, color in enumerate(linear_hex_colors): brightness = 0.299 * linear_colors[i][0] + 0.587 * linear_colors[i][1] + 0.114 * linear_colors[i][2] text_color = 'white' if brightness < 0.5 else 'black' table.tab_style( style=[ ('background-color', color), ('color', text_color) ], locations=['cells'], rows=i+1, columns='value_linear' ) # Apply log color scale to value_skewed column log_values = pldf['value_skewed'].to_list() log_domain = (min(log_values), max(log_values)) log_hex_colors = log_color_mapper(log_values, palette='viridis', domain=log_domain) # Get text colors based on background brightness log_colors = [plt.colors.hex2color(color) for color in log_hex_colors] text_colors = ['white' if (0.299 * r + 0.587 * g + 0.114 * b) < 0.5 else 'black' for r, g, b in log_colors] for i, (color, text_color) in enumerate(zip(log_hex_colors, text_colors)): table.tab_style( style=[ ('background-color', color), ('color', text_color) ], locations=['cells'], rows=i+1, columns='value_skewed' ) # Add explanatory notes table.tab_source_note( source_note="value_linear uses a linear color scale (Blues)" ) table.tab_source_note( source_note="value_skewed uses a logarithmic color scale (Viridis)" ) # Display the table tableIf you're using a newer version of gt that supports data_color with custom color functions, you could potentially simplify this further:
import polars as pl import numpy as np from gt import GT import matplotlib.pyplot as plt from matplotlib.colors import LogNorm # Create sample data data = { 'category': list('ABCDEFGH'), 'value_linear': [1, 5, 10, 20, 50, 100, 150, 200], 'value_skewed': [0.1, 1, 10, 100, 1000, 10000, 100000, 1000000] } # Create a Polars DataFrame pldf = pl.DataFrame(data) # Create the GT table table = GT(pldf) # Format numeric columns table.fmt_number( columns=['value_linear', 'value_skewed'], decimals=1, use_seps=True ) # Add title table.tab_header( title="Log-Scaled Color Mapping in Tables", subtitle="Using gt with Polars DataFrame" ) # Define a custom color function for log scale def log_scale_palette(x, palette='viridis', domain=None): """Create a color palette function that uses log scaling""" if domain is None: domain = (min(filter(lambda v: v > 0, x)), max(x)) def color_fn(value): # Handle zeros and negative values if value <= 0: value = domain[0] / 10 # Create log normalization norm = LogNorm(vmin=domain[0], vmax=domain[1]) # Get colormap cmap = plt.cm.get_cmap(palette) # Return color return plt.colors.rgb2hex(cmap(norm(value))) return color_fn # Apply data_color with appropriate scales # Note: This approach assumes your version of gt supports custom color functions # If not, use the previous example with tab_style # For linear scale table.data_color( columns='value_linear', colors=plt.cm.Blues, autocolor_text=True ) # For log scale (if supported) log_values = pldf['value_skewed'].to_list() log_domain = (min(filter(lambda v: v > 0, log_values)), max(log_values)) # This part depends on gt's implementation details and may need adjustment table.data_color( columns='value_skewed', colors=log_scale_palette(log_values, domain=log_domain), autocolor_text=True ) # Add explanatory notes table.tab_source_note( source_note="value_linear uses a linear color scale (Blues)" ) table.tab_source_note( source_note="value_skewed uses a logarithmic color scale (Viridis)" ) # Display the table tableNote that the exact implementation details may vary depending on your specific version of gt and how it integrates with Polars. The first two examples should work with most setups, while the third example assumes more advanced integration between gt and custom color functions.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.