Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Lets-Plot
https://github.com/jetbrains/lets-plot
Admin
Lets-Plot is a multiplatform plotting library built on the principles of the Grammar of Graphics,
...
Tokens:
646,484
Snippets:
3,476
Trust Score:
9.5
Update:
2 months ago
Context
Skills
Chat
Benchmark
84.9
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Lets-Plot Lets-Plot is a multiplatform plotting library built on the principles of the Grammar of Graphics, heavily influenced by Leland Wilkinson's foundational work and Hadley Wickham's ggplot2. The library provides a declarative approach to data visualization where plots are constructed by composing independent graphical components - data, aesthetic mappings, geometric objects, statistical transformations, scales, coordinate systems, and facets. This modular design enables creating precisely tailored graphics rather than being limited to pre-specified chart types. The library supports multiple platforms including Python (via pip), Kotlin (for notebooks, Compose Multiplatform, JVM/Swing, JavaFX, and Kotlin/JS), and integrates with JetBrains IDEs through the "Lets-Plot in SciView" plugin. Lets-Plot works seamlessly in Jupyter notebooks, Datalore, Google Colab, and other notebook environments, providing interactive visualizations with features like pan/zoom, tooltips, and live maps. ## Core API ### Basic Plot Construction with ggplot() The `ggplot()` function creates a base plot object that layers are added to using the `+` operator. Data is passed as a DataFrame and aesthetic mappings define how data variables map to visual properties. ```python import pandas as pd from lets_plot import * LetsPlot.setup_html() # Load sample data mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") # Create scatter plot with color mapping plot = (ggplot(mpg, aes(x='displ', y='hwy', color='drv')) + geom_point(size=3, alpha=0.7) + labs(title="Highway MPG vs Engine Displacement", x="Engine Displacement (L)", y="Highway MPG", color="Drive Type") + theme_minimal()) plot # Output: Interactive scatter plot showing relationship between engine size and fuel efficiency ``` ### geom_point() - Scatter Plots Creates scatter plots displaying individual data points. Supports aesthetics for position, color, size, shape, and transparency. ```python from lets_plot import * import numpy as np LetsPlot.setup_html() np.random.seed(42) data = { 'x': np.random.normal(0, 1, 200), 'y': np.random.normal(0, 1, 200), 'category': np.random.choice(['A', 'B', 'C'], 200), 'value': np.random.uniform(1, 10, 200) } (ggplot(data, aes('x', 'y')) + geom_point(aes(color='category', size='value'), alpha=0.6, shape=21, stroke=1) + scale_color_brewer(palette='Set2') + scale_size(range=[2, 8]) + coord_fixed() + theme_bw()) # Output: Scatter plot with points colored by category and sized by value ``` ### geom_line() and geom_path() - Line Plots Draws lines connecting data points. `geom_line()` connects points in order of x-values, while `geom_path()` connects in data order. ```python from lets_plot import * import pandas as pd import numpy as np LetsPlot.setup_html() x = np.linspace(0, 4 * np.pi, 100) data = pd.DataFrame({ 'x': np.tile(x, 3), 'y': np.concatenate([np.sin(x), np.cos(x), np.sin(x) * np.cos(x)]), 'function': np.repeat(['sin(x)', 'cos(x)', 'sin(x)*cos(x)'], 100) }) (ggplot(data, aes('x', 'y', color='function')) + geom_line(size=1.2) + scale_color_manual(values=['#e41a1c', '#377eb8', '#4daf4a']) + labs(title="Trigonometric Functions", x="x", y="y") + theme_classic()) # Output: Multi-line plot showing three trigonometric functions ``` ### geom_bar() and geom_histogram() - Bar Charts Creates bar charts for categorical data or histograms for continuous distributions. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() data = pd.DataFrame({ 'category': ['Product A', 'Product B', 'Product C', 'Product D', 'Product E'], 'sales': [120, 200, 150, 80, 170], 'region': ['North', 'South', 'North', 'South', 'North'] }) # Grouped bar chart (ggplot(data, aes('category', 'sales', fill='region')) + geom_bar(stat='identity', position='dodge', width=0.7) + scale_fill_brewer(palette='Pastel1') + labs(title="Sales by Product and Region", y="Sales ($K)") + theme(axis_text_x=element_text(angle=45, hjust=1))) # Output: Grouped bar chart showing sales comparison # Histogram with custom bins import numpy as np hist_data = {'values': np.random.exponential(scale=2, size=1000)} (ggplot(hist_data, aes('values')) + geom_histogram(bins=30, fill='steelblue', color='white', alpha=0.8) + geom_density(color='red', size=1.5) + labs(title="Distribution with Density Overlay")) # Output: Histogram with overlaid density curve ``` ### geom_boxplot() and geom_violin() - Distribution Visualization Displays statistical summaries of data distributions using box plots or violin plots. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") # Combined violin and boxplot (ggplot(mpg, aes('class', 'hwy', fill='class')) + geom_violin(alpha=0.3, show_legend=False) + geom_boxplot(width=0.2, outlier_shape=21) + coord_flip() + labs(title="Highway MPG by Vehicle Class", x="Vehicle Class", y="Highway MPG") + theme_minimal() + theme(legend_position='none')) # Output: Violin plots with embedded boxplots showing distribution by vehicle class ``` ### geom_sina() - Sina Plots Jittered strip chart that respects violin shape, showing individual data points distributed according to local density. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") (ggplot(mpg, aes('drv', 'cty')) + geom_violin(size=0, fill='#dddddd', alpha=0.5) + geom_sina(aes(color='..quantile..'), seed=42, quantiles=[0.25, 0.5, 0.75]) + scale_color_viridis() + labs(title="City MPG by Drive Type", x="Drive Type", y="City MPG") + theme_bw()) # Output: Sina plot showing individual points shaped by violin density ``` ### geom_pointdensity() - Point Density Plots Scatter plot where each point is colored based on local point density - dense clusters get one color, sparse areas another. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() diamonds = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/refs/heads/master/data/diamonds.csv") fair_cut = diamonds[diamonds['cut'] == 'Fair'] (ggplot(fair_cut, aes('carat', 'price')) + geom_pointdensity(aes(color='..count..'), adjust=0.5) + scale_color_viridis(name="Neighbor Count") + labs(title="Diamond Price vs Carat (Fair Cut)", subtitle="Points colored by local density") + theme_classic()) # Output: Scatter plot with points colored by local density ``` ### geom_hex() - Hexagonal Binning Divides the plane into hexagonal bins and counts points in each, useful for large datasets. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() diamonds = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/refs/heads/master/data/diamonds.csv") (ggplot(diamonds, aes('carat', 'price')) + geom_hex(bins=30) + scale_fill_viridis(trans='log10', name="Count") + labs(title="Diamond Price Distribution (53,940 points)") + theme_minimal()) # Output: Hexagonal heatmap showing point density ``` ### geom_smooth() - Trend Lines Adds smoothed conditional means with confidence intervals using various methods (loess, lm, etc.). ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") (ggplot(mpg, aes('displ', 'hwy')) + geom_point(aes(color='drv'), alpha=0.5) + geom_smooth(aes(color='drv'), method='loess', se=True, span=0.8) + labs(title="Highway MPG vs Displacement with LOESS Smoothing") + theme_bw()) # Output: Scatter plot with smoothed trend lines per drive type ``` ### geom_tile() and geom_raster() - Heatmaps Creates rectangular tiles for heatmap visualizations. ```python from lets_plot import * import numpy as np import pandas as pd LetsPlot.setup_html() # Create correlation matrix heatmap np.random.seed(42) n_vars = 6 data = np.random.randn(100, n_vars) corr = np.corrcoef(data.T) vars = [f'Var{i+1}' for i in range(n_vars)] heatmap_data = pd.DataFrame([ {'x': vars[i], 'y': vars[j], 'correlation': corr[i, j]} for i in range(n_vars) for j in range(n_vars) ]) (ggplot(heatmap_data, aes('x', 'y', fill='correlation')) + geom_tile(color='white', size=0.5) + geom_text(aes(label='correlation'), format='.2f', size=8) + scale_fill_gradient2(low='#2166ac', mid='white', high='#b2182b', midpoint=0) + coord_fixed() + labs(title="Correlation Matrix") + theme(axis_title='blank')) # Output: Correlation matrix heatmap with values displayed ``` ### geom_text() and geom_label() - Text Annotations Adds text labels to plots, with `geom_label()` adding a background box. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() data = pd.DataFrame({ 'x': [1, 2, 3, 4, 5], 'y': [2, 4, 3, 5, 4], 'label': ['Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon'] }) (ggplot(data, aes('x', 'y')) + geom_point(size=5, color='steelblue') + geom_label(aes(label='label'), nudge_y=0.3, fill='white', alpha=0.8, label_padding=0.3) + labs(title="Points with Labels") + expand_limits(y=[1, 6])) # Output: Scatter plot with labeled points ``` ### geom_text_repel() and geom_label_repel() - Non-overlapping Labels Automatically positions text labels to avoid overlaps using force-directed layout. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() data = pd.DataFrame({ 'x': [1, 1.1, 2, 2.1, 3], 'y': [1, 1.1, 2, 2.1, 3], 'label': ['Point A', 'Point B', 'Point C', 'Point D', 'Point E'] }) (ggplot(data, aes('x', 'y')) + geom_point(size=4, color='red') + geom_text_repel(aes(label='label'), max_overlaps=20, box_padding=0.5, point_padding=0.3) + labs(title="Non-overlapping Labels")) # Output: Points with automatically positioned non-overlapping labels ``` ### geom_pie() - Pie Charts Creates pie charts with support for donut charts and annotations. ```python from lets_plot import * LetsPlot.setup_html() data = { 'category': ['Electronics', 'Clothing', 'Food', 'Books', 'Other'], 'value': [35, 25, 20, 12, 8] } (ggplot(data) + geom_pie(aes(fill='category', slice='value'), stat='identity', hole=0.4, # Creates donut chart stroke=1, stroke_side='both', labels=layer_labels().line('@category').line('@value%')) + labs(title="Sales Distribution by Category") + coord_fixed() + theme_void()) # Output: Donut chart with category labels and percentages ``` ### geom_segment() and geom_curve() - Lines and Curves Draws line segments or curves between points, useful for annotations and graph visualizations. ```python from lets_plot import * LetsPlot.setup_html() # Network-style visualization nodes = {'x': [0, 1, 2, 1], 'y': [0, 1, 0, -1], 'label': ['A', 'B', 'C', 'D']} edges = { 'x': [0, 0, 1, 1], 'y': [0, 0, 1, -1], 'xend': [1, 2, 2, 2], 'yend': [1, 0, 0, 0] } (ggplot() + geom_curve(aes(x='x', y='y', xend='xend', yend='yend'), data=edges, curvature=0.2, arrow=arrow(length=10, type='closed')) + geom_point(aes('x', 'y'), data=nodes, size=10, color='steelblue') + geom_text(aes('x', 'y', label='label'), data=nodes, color='white', fontface='bold') + coord_fixed() + theme_void() + labs(title="Network Graph")) # Output: Simple network graph with curved edges and labeled nodes ``` ### geom_livemap() - Interactive Maps Creates interactive tile-based maps with support for various tile providers and geographic data. ```python from lets_plot import * LetsPlot.setup_html() # Cities data cities = { 'city': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix'], 'lon': [-74.006, -118.244, -87.630, -95.370, -112.074], 'lat': [40.713, 34.052, 41.878, 29.760, 33.449], 'population': [8.3, 4.0, 2.7, 2.3, 1.6] } (ggplot(cities, aes('lon', 'lat')) + geom_livemap() + geom_point(aes(size='population'), color='red', alpha=0.7) + geom_text(aes(label='city'), nudge_y=0.5, color='darkred') + scale_size(range=[5, 15], name="Population (M)") + ggtitle("Major US Cities by Population")) # Output: Interactive map with city markers sized by population ``` ## Scales ### Color Scales Control color mappings for data visualization with various palettes and gradients. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() diamonds = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/refs/heads/master/data/diamonds.csv") sample = diamonds.sample(500, random_state=42) # Viridis scale for continuous data p1 = (ggplot(sample, aes('carat', 'price', color='depth')) + geom_point(alpha=0.7) + scale_color_viridis(option='plasma') + ggtitle("Viridis Plasma")) # Brewer scale for discrete data p2 = (ggplot(sample, aes('carat', 'price', color='cut')) + geom_point(alpha=0.7) + scale_color_brewer(palette='Set1') + ggtitle("Brewer Set1")) # Gradient2 scale with midpoint p3 = (ggplot(sample, aes('carat', 'price', color='depth')) + geom_point(alpha=0.7) + scale_color_gradient2(low='blue', mid='white', high='red', midpoint=62) + ggtitle("Gradient2")) gggrid([p1, p2, p3], ncol=3) # Output: Three plots demonstrating different color scales ``` ### Position Scales Configure axis transformations, limits, and breaks. ```python from lets_plot import * import numpy as np LetsPlot.setup_html() data = {'x': np.logspace(0, 4, 50), 'y': np.logspace(0, 4, 50) * (1 + 0.1*np.random.randn(50))} (ggplot(data, aes('x', 'y')) + geom_point() + geom_smooth(method='lm') + scale_x_log10(name="X (log scale)") + scale_y_log10(name="Y (log scale)", format=".0e") + labs(title="Log-Log Plot")) # Output: Scatter plot with logarithmic axes ``` ### DateTime Scales Handle temporal data with automatic formatting and appropriate breaks. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() dates = pd.date_range('2024-01-01', periods=365, freq='D') data = pd.DataFrame({ 'date': dates, 'value': 100 + np.cumsum(np.random.randn(365) * 2) }) (ggplot(data, aes('date', 'value')) + geom_line(color='steelblue') + geom_smooth(color='red', se=False, span=0.3) + scale_x_datetime(format="%b %Y") + labs(title="Time Series with Trend", x="Date", y="Value") + theme_minimal()) # Output: Time series line chart with formatted date axis ``` ## Faceting ### facet_wrap() - Wrap Panels Creates a grid of panels wrapping into rows, useful when faceting by a single variable with many levels. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") (ggplot(mpg, aes('displ', 'hwy')) + geom_point(aes(color='drv'), alpha=0.7) + geom_smooth(method='lm', se=False, color='black') + facet_wrap('class', ncol=4, scales='free_y') + labs(title="Highway MPG vs Displacement by Vehicle Class") + theme_bw() + theme(strip_background=element_rect(fill='lightblue'))) # Output: Grid of scatter plots, one per vehicle class ``` ### facet_grid() - Grid Layout Creates a matrix of panels defined by row and column faceting variables. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") (ggplot(mpg, aes('cty', 'hwy')) + geom_point(alpha=0.5) + geom_abline(slope=1, intercept=0, linetype='dashed', color='red') + facet_grid(x='drv', y='cyl', scales='free') + labs(title="City vs Highway MPG", subtitle="By Drive Type (columns) and Cylinders (rows)") + theme_light()) # Output: Matrix of scatter plots faceted by drive type and cylinders ``` ## Themes and Styling ### Built-in Themes Apply pre-configured visual styles to plots. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") p = ggplot(mpg, aes('displ', 'hwy', color='drv')) + geom_point() gggrid([ p + theme_grey() + ggtitle("theme_grey()"), p + theme_bw() + ggtitle("theme_bw()"), p + theme_minimal() + ggtitle("theme_minimal()"), p + theme_classic() + ggtitle("theme_classic()"), p + theme_light() + ggtitle("theme_light()"), p + theme_void() + ggtitle("theme_void()") ], ncol=3, widths=[400, 400, 400]) # Output: Same plot with six different themes ``` ### Theme Flavors Apply color schemes to existing themes for different visual contexts. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") p = (ggplot(mpg, aes('displ', 'hwy', color='drv')) + geom_point() + theme_minimal()) gggrid([ p + ggtitle("Default"), p + flavor_darcula() + ggtitle("Darcula"), p + flavor_solarized_light() + ggtitle("Solarized Light"), p + flavor_solarized_dark() + ggtitle("Solarized Dark"), p + flavor_high_contrast_light() + ggtitle("High Contrast Light"), p + flavor_high_contrast_dark() + ggtitle("High Contrast Dark") ], ncol=3) # Output: Same plot with six different flavor color schemes ``` ### Custom Theme Elements Fine-tune plot appearance with theme() parameters. ```python from lets_plot import * LetsPlot.setup_html() data = {'x': ['A', 'B', 'C', 'D'], 'y': [4, 7, 3, 8]} (ggplot(data, aes('x', 'y')) + geom_bar(stat='identity', fill='steelblue') + labs(title="Custom Styled Plot", subtitle="With theme customization") + theme( plot_title=element_text(size=18, face='bold', hjust=0.5, color='navy'), plot_subtitle=element_text(size=12, face='italic', hjust=0.5), axis_title=element_text(size=12, face='bold'), axis_text_x=element_text(angle=45, hjust=1, size=10), panel_background=element_rect(fill='#f5f5f5'), panel_grid_major=element_line(color='white', size=1), panel_grid_minor=element_blank(), legend_position='bottom' )) # Output: Bar chart with extensively customized theme elements ``` ## Plot Composition ### gggrid() - Combine Multiple Plots Arranges multiple plots in a grid layout with optional shared axes and legends. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") p1 = ggplot(mpg, aes('displ', 'hwy')) + geom_point() + ggtitle("Scatter") p2 = ggplot(mpg, aes('hwy')) + geom_histogram(bins=20) + ggtitle("Histogram") p3 = ggplot(mpg, aes('drv', 'hwy')) + geom_boxplot() + ggtitle("Boxplot") p4 = ggplot(mpg, aes('class')) + geom_bar() + coord_flip() + ggtitle("Bar") gggrid([p1, p2, p3, p4], ncol=2, widths=[500, 500], heights=[300, 300]) # Output: 2x2 grid of four different plot types ``` ### ggbunch() - Free-form Layout Places plots at arbitrary positions for custom layouts. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") main_plot = (ggplot(mpg, aes('displ', 'hwy', color='drv')) + geom_point() + theme_minimal()) inset_plot = (ggplot(mpg, aes('drv', fill='drv')) + geom_bar() + theme_void() + theme(legend_position='none')) bunch = ggbunch() bunch.add_plot(main_plot, 0, 0, 600, 400) bunch.add_plot(inset_plot, 400, 50, 180, 150) # Inset in corner bunch # Output: Main scatter plot with bar chart inset ``` ## Interactivity ### ggtb() - Pan and Zoom Toolbar Enables interactive pan and zoom functionality on plots. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() diamonds = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/refs/heads/master/data/diamonds.csv") sample = diamonds.sample(2000, random_state=42) (ggplot(sample, aes('carat', 'price', color='cut')) + geom_point(alpha=0.6) + ggtb() # Adds interactive toolbar + scale_color_brewer(palette='Set1') + labs(title="Interactive Diamond Data (use toolbar to pan/zoom)") + theme_bw()) # Output: Interactive scatter plot with pan/zoom toolbar # - Drag to pan # - Mouse wheel to zoom # - Double-click to reset ``` ### Tooltips Customization Configure rich tooltips with custom formatting and content. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") (ggplot(mpg, aes('displ', 'hwy', color='class')) + geom_point( tooltips=layer_tooltips() .title("@manufacturer @model") .line("Year: @year") .line("Engine: @displ L, @cyl cylinders") .line("MPG: @cty city / @hwy highway") .format('@displ', '.1f') ) + labs(title="Hover over points for details")) # Output: Scatter plot with rich custom tooltips ``` ## Statistical Functions ### stat_summary() - Statistical Summaries Computes and displays statistical summaries of data. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") (ggplot(mpg, aes('class', 'hwy')) + geom_jitter(alpha=0.3, width=0.2) + stat_summary(fun='mean', geom='point', color='red', size=4) + stat_summary(fun='mean', geom='errorbar', fun_min='min', fun_max='max', color='red', width=0.3) + labs(title="Highway MPG by Class with Mean and Range") + coord_flip()) # Output: Strip plot with mean points and range error bars ``` ### stat_ecdf() - Empirical CDF Plots the empirical cumulative distribution function. ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") (ggplot(mpg, aes('hwy', color='drv')) + stat_ecdf(size=1.2) + labs(title="Empirical CDF of Highway MPG", x="Highway MPG", y="Cumulative Probability") + theme_minimal()) # Output: ECDF curves for each drive type ``` ## Bistro Module - High-level Plots ### waterfall_plot() - Waterfall Charts Creates waterfall charts showing cumulative effects of sequential values. ```python from lets_plot import * from lets_plot.bistro import * LetsPlot.setup_html() data = { "Category": ["Starting", "Product Sales", "Service Revenue", "Costs", "Marketing", "Final"], "Amount": [1000000, 450000, 200000, -300000, -150000, None], "Measure": ['absolute', 'relative', 'relative', 'relative', 'relative', 'total'] } (waterfall_plot(data, "Category", "Amount", measure="Measure") + scale_y_continuous(format="$,.0f") + labs(title="Revenue Waterfall Analysis") + theme_minimal()) # Output: Waterfall chart showing revenue flow ``` ### corr_plot() - Correlation Plots Creates correlation matrix visualizations. ```python from lets_plot import * from lets_plot.bistro.corr import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") numeric_cols = mpg[['displ', 'cyl', 'cty', 'hwy']] (corr_plot(numeric_cols) .points() .labels() .build() + ggtitle("Correlation Matrix")) # Output: Correlation matrix with points and labels ``` ### qq_plot() - Q-Q Plots Creates quantile-quantile plots for distribution comparison. ```python from lets_plot import * from lets_plot.bistro.qq import * import numpy as np LetsPlot.setup_html() np.random.seed(42) data = {'values': np.random.normal(0, 1, 200)} (qq_plot(data, 'values', distribution='norm') + labs(title="Q-Q Plot: Sample vs Normal Distribution") + theme_light()) # Output: Q-Q plot comparing sample to normal distribution ``` ## Export and Output ### ggsave() - Save Plots to Files Exports plots to various file formats (SVG, HTML, PNG, PDF). ```python from lets_plot import * import pandas as pd LetsPlot.setup_html() mpg = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv") plot = (ggplot(mpg, aes('displ', 'hwy', color='drv')) + geom_point() + labs(title="Highway MPG vs Engine Displacement") + theme_minimal()) # Save to different formats ggsave(plot, "plot.svg") # SVG vector format ggsave(plot, "plot.html") # Interactive HTML ggsave(plot, "plot.png", dpi=300) # High-resolution PNG ggsave(plot, "plot.pdf", w=8, h=6, unit='in') # PDF with size # Export to string svg_string = plot.to_svg() html_string = plot.to_html() ``` ### Setup and Configuration Initialize Lets-Plot for different environments. ```python from lets_plot import * # For Jupyter notebooks LetsPlot.setup_html() # For offline mode (no CDN) LetsPlot.setup_html(offline=True) # Set default theme for all plots LetsPlot.set_theme(theme_minimal()) # External browser display LetsPlot.setup_show_ext() # Opens plots in browser ``` ## Summary Lets-Plot provides a comprehensive Grammar of Graphics implementation for Python and Kotlin, enabling the construction of sophisticated statistical visualizations through composable layers. The library excels at exploratory data analysis with its extensive geometry types (points, lines, bars, boxes, violins, hexbins, maps, and more), powerful faceting for multi-panel displays, and rich theming system with both built-in themes and color flavors. Interactive features like pan/zoom toolbars, customizable tooltips, and live maps make it particularly suitable for notebook-based data exploration. The library integrates seamlessly with pandas DataFrames and supports common data science workflows including correlation analysis, distribution visualization, time series plotting, and geographic data mapping. For production use, plots can be exported to SVG, HTML, PNG, or PDF formats with configurable resolution. The bistro module provides high-level convenience functions for common chart types like waterfall plots, correlation matrices, and Q-Q plots, while the core API allows fine-grained control over every visual aspect through the theme system and scale customization.