Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Plotly DataFrame Visualization Guide

Create interactive visualizations directly from pandas DataFrames with Plotly Express and graph_objects. Covers line charts, scatter plots, bar charts, time series, performance, and layout customization.

~4 min readPython
#plotly#pandas#data visualization#python
A line chart and bar chart generated from a pandas DataFrame using Plotly, with interactive hover tooltips and a clean layout.

When you need to turn a pandas DataFrame into an interactive chart, Plotly offers a direct route that avoids the boilerplate of low-level plotting libraries. This article shows how to map DataFrame columns to Plotly traces, customize the output, and handle common data shapes without losing Plotly's interactivity.

Creating a Line Chart from a DataFrame

Plotly Express is the quickest way to produce a line chart from a DataFrame. The px.line function accepts a DataFrame and column names for the x and y axes. For example:

python
import pandas as pd import plotly.express as px df = pd.DataFrame({ 'x': [1, 2, 3, 4], 'y': [10, 11, 12, 13] }) fig = px.line(df, x='x', y='y') fig.show()

This creates an interactive line chart where hovering reveals the exact values. The x and y arguments can be any column names. If your DataFrame has a datetime column, Plotly automatically formats the axis as a time series, which we will cover later.

Scatter Plots and Customizing Markers

Scatter plots are equally straightforward. px.scatter maps columns to x, y, and optionally color, size, and hover_data. This is useful for exploring relationships between numeric columns.

python
import plotly.express as px df = pd.DataFrame({ 'height': [160, 170, 175, 180], 'weight': [55, 65, 70, 80], 'gender': ['F', 'M', 'M', 'M'] }) fig = px.scatter(df, x='height', y='weight', color='gender', size='weight', hover_data=['height', 'weight']) fig.show()

The color parameter adds a legend and colors points by the unique values in that column. The size parameter scales marker size proportionally to the numeric column. This makes it easy to encode multiple dimensions in one chart without writing low-level layout code.

Bar Charts and Aggregated Data

Bar charts often require aggregated data. Plotly Express provides px.bar, which can work directly with a DataFrame or with pre-aggregated values. If your data has repeated categories for the same bar, aggregate with pandas first, then pass the result to px.bar.

python
import pandas as pd import plotly.express as px df = pd.DataFrame({ 'product': ['A', 'B', 'A', 'B', 'A', 'C'], 'sales': [100, 150, 120, 170, 130, 90], 'region': ['North', 'South', 'South', 'North', 'North', 'South'] }) agg = df.groupby('product')['sales'].sum().reset_index() fig = px.bar(agg, x='product', y='sales') fig.show()

To compare sales by product and region, aggregate by both columns first:

python
agg_region = df.groupby(['product', 'region'])['sales'].sum().reset_index() fig = px.bar(agg_region, x='product', y='sales', color='region', barmode='group') fig.show()

If the DataFrame already has one row per category combination, you can skip the groupby and pass it directly to px.bar.

Using graph_objects for More Control

While Plotly Express covers most common charts, plotly.graph_objects gives you finer control over each trace. This is useful when you need to combine multiple chart types or precisely adjust trace properties.

python
import plotly.graph_objects as go df = pd.DataFrame({ 'x': [1, 2, 3, 4], 'y': [10, 11, 12, 13] }) fig = go.Figure() fig.add_trace(go.Scatter(x=df['x'], y=df['y'], mode='lines+markers', name='Data Series')) fig.update_layout(title='Custom Scatter', xaxis_title='X', yaxis_title='Y') fig.show()

The go.Scatter trace accepts mode to control whether lines, markers, or both are displayed. You can add multiple traces to the same figure, each with its own data and styling. This approach is more verbose than Express but necessary when you need to mix chart types or apply advanced trace-level settings.

Handling Time Series Data

Plotly handles datetime columns automatically, but you must ensure the column is a datetime type in pandas. For example:

python
import pandas as pd import plotly.express as px df = pd.DataFrame({ 'date': pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03']), 'value': [10, 15, 12] }) fig = px.line(df, x='date', y='value') fig.show()

Plotly will format the x-axis with date ticks and allow zooming into time ranges. If your data is irregularly spaced, Plotly still connects the points in the order they appear, so sort by date first if you need a chronological line. For large time series, consider WebGL rendering or downsampling, as discussed next.

Performance Considerations with Large DataFrames

Interactive charts can become sluggish when a DataFrame has hundreds of thousands of rows. Plotly offers several strategies to keep the visualization responsive.

First, use WebGL rendering when it fits your chart. For a DataFrame with numeric columns named x and y, px.scatter has a render_mode parameter; setting render_mode='webgl' uses WebGL for hardware-accelerated rendering. For line charts with many points, use go.Scattergl instead of go.Scatter.

python
fig = px.scatter(df, x='x', y='y', render_mode='webgl')

Second, downsample the data before plotting. If you only need to see the overall trend, you can sample every nth row or aggregate by time bins. For example:

python
sampled = df.iloc[::10, :] # take every 10th row fig = px.line(sampled, x='date', y='value')

This reduces the number of points sent to the browser, improving responsiveness without a noticeable loss of detail for many use cases.

Third, avoid using hover_data with many columns on large datasets, as it increases the amount of data embedded in the figure. Instead, limit hover information to the essential fields.

Customizing Layout and Interactivity

Plotly figures are highly customizable through update_layout. You can set titles, axis ranges, grid lines, and even add annotations. For example:

python
fig.update_layout( title='Sales by Product', xaxis_title='Product', yaxis_title='Revenue', legend_title='Region', template='plotly_white' )

The template parameter changes the overall style. Common options include 'plotly', 'plotly_white', 'plotly_dark', and 'seaborn'. You can also control interactivity: fig.update_xaxes(rangeslider_visible=True) adds a range slider for time series, and fig.update_layout(hovermode='x unified') changes how hover tooltips behave.

For more advanced interactivity, you can add callbacks in a Dash app, but for standalone charts the built-in hover, zoom, and pan features are usually sufficient.

When you are ready to share the chart, fig.write_html('chart.html') saves a self-contained HTML file that works in any browser. You can also convert it to a static image with fig.write_image('chart.png') if you have the kaleido package installed, but that is an optional dependency.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.