importplotly.ioaspio# Set default rendererpio.renderers.default='browser'# or 'notebook', 'jupyterlab', 'vscode'# Check available renderersprint(pio.renderers)# Set default templatepio.templates.default='plotly_dark'# Available templates: plotly, plotly_white, plotly_dark, ggplot2, # seaborn, simple_white, none
Use Case 1: Time Series Analysis with Range Slider¶
importplotly.expressaspximportpandasaspd# Create time series datadf=pd.DataFrame({'date':pd.date_range('2023-01-01',periods=365),'value':np.random.randn(365).cumsum()})# Create interactive time seriesfig=px.line(df,x='date',y='value',title='Time Series with Range Slider')# Add range slider and buttonsfig.update_xaxes(rangeslider_visible=True,rangeselector=dict(buttons=list([dict(count=1,label="1m",step="month",stepmode="backward"),dict(count=6,label="6m",step="month",stepmode="backward"),dict(count=1,label="YTD",step="year",stepmode="todate"),dict(count=1,label="1y",step="year",stepmode="backward"),dict(step="all")])))fig.show()
importplotly.expressaspximportpandasaspdimportnumpyasnp# Create sample correlation matrixdf=pd.DataFrame(np.random.randn(100,5),columns=['A','B','C','D','E'])corr_matrix=df.corr()# Create annotated heatmapfig=px.imshow(corr_matrix,text_auto='.2f',# Show values with 2 decimal placesaspect='auto',color_continuous_scale='RdBu_r',# Red-Blue reversedzmin=-1,zmax=1# Correlation range)fig.update_layout(title='Correlation Matrix',xaxis_title='Variables',yaxis_title='Variables')fig.show()
Use Case 4: Interactive 3D Scatter with Custom Hover¶
importplotly.expressaspximportpandasaspdimportnumpyasnp# Create 3D datasetdf=pd.DataFrame({'x':np.random.randn(200),'y':np.random.randn(200),'z':np.random.randn(200),'category':np.random.choice(['A','B','C'],200),'size':np.random.randint(5,30,200),'label':[f'Point {i}'foriinrange(200)]})# Create 3D scatterfig=px.scatter_3d(df,x='x',y='y',z='z',color='category',size='size',hover_data=['label','size'],title='3D Scatter Plot with Categories')# Customize 3D scenefig.update_layout(scene=dict(xaxis_title='X Axis',yaxis_title='Y Axis',zaxis_title='Z Axis',camera=dict(eye=dict(x=1.5,y=1.5,z=1.5))))fig.show()
importplotly.expressaspx# Create data with time dimensiondf=pd.DataFrame({'year':[2020]*5+[2021]*5+[2022]*5,'country':['A','B','C','D','E']*3,'gdp':np.random.randint(1000,5000,15),'population':np.random.randint(10,100,15)})# Create animated scatterfig=px.scatter(df,x='gdp',y='population',animation_frame='year',animation_group='country',size='population',color='country',hover_name='country',size_max=55,range_x=[0,6000],range_y=[0,120],title='GDP vs Population Over Time')fig.update_layout(transition_duration=500)fig.show()
Use Plotly Express for rapid prototyping: Start with px for quick visualizations, then switch to go (Graph Objects) when you need fine-grained control over every element
Leverage templates for consistency: Set a default template with pio.templates.default to maintain consistent styling across all visualizations in your project
Optimize for large datasets: For datasets with >10k points, consider using scattergl instead of scatter, or use datashader for pre-aggregation before plotting
Make visualizations accessible: Always include axis labels, titles, and legends. Use colorblind-friendly palettes like plotly.colors.qualitative.Safe
Export considerations: Use kaleido for high-quality static exports. For web embedding, use fig.write_html(include_plotlyjs='cdn') to reduce file size
Interactive features: Enable hovermode='x unified' for time series to compare multiple traces at the same x-value simultaneously
Memory management: When creating multiple figures in loops, explicitly call fig = None or use context managers to free memory
Version control: Save figure configurations as JSON with fig.to_json() for reproducibility and version control of visualizations