Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Plotly Express: Line, Bar, Scatter, Pie, Histogram

Learn how to create line, bar, scatter, pie, and histogram charts with Python Plotly Express, including data mapping, key parameters, and customization.

~6 min readPython
#plotly#data visualization#python#charts
A clean illustration showing five distinct chart types—line, bar, scatter, pie, and histogram—arranged in a grid, representing Plotly Express chart creation in Python.

When you need line, bar, scatter, pie, and histogram charts from a pandas DataFrame, Plotly Express provides a concise API that turns the data into an interactive figure with a single function call. The functions for these common chart types let you explore and report data quickly. Instead of manually building traces with plotly.graph_objects, Express removes the boilerplate and lets you focus on how columns map to visual channels.

Why Plotly Express for Common Chart Types

Plotly Express is designed for rapid iteration. Each chart function accepts a DataFrame and maps columns to visual channels like x, y, color, size, and facet. The resulting figure is interactive and can be shown in Jupyter, saved to HTML, or embedded in web pages. For developers who need to inspect data quickly or build dashboards, Express can remove much of the setup required when constructing traces directly with graph_objects.

The typical Express workflow works well with tidy data: each row is an observation, each column is a variable. This aligns with how most data is stored in pandas, so you can often plot without reshaping data first.

Line Charts with plotly.express.line

A line chart is appropriate when you want to show a trend over a continuous variable, typically time. The line function maps x to the independent axis and y to the dependent variable. If you pass multiple columns to y, each becomes a separate line.

python
import plotly.express as px import pandas as pd df = pd.DataFrame({ "date": pd.date_range("2024-01-01", periods=12, freq="ME"), "sales": [120, 135, 142, 158, 162, 175, 190, 205, 210, 230, 245, 260] }) fig = px.line(df, x="date", y="sales", title="Monthly Sales Trend") fig.show()

When your data has a categorical column that splits the lines, use color to create a grouped line chart. For example, if you have sales per region, pass color="region" and each region gets its own line with a legend. The markers parameter adds point markers, which is useful when the data is sparse or you want to highlight individual observations.

One common mistake is using a line chart when the x values are not in the order you intend. Plotly connects the points in the order they appear in the DataFrame for the requested mapping, which can produce misleading zigzags if rows are not sorted by x. Sort the DataFrame before plotting if the natural order matters.

Bar Charts with plotly.express.bar

Bar charts compare categorical values or show a distribution across discrete bins. The bar function works similarly to line but draws rectangular bars. If your DataFrame is already aggregated, map a categorical column to x and the numeric column to y. For a simple count of categories, you can pass a single column to x and omit y; Plotly will count occurrences.

python
import plotly.express as px df = px.data.tips() # built-in dataset fig = px.bar(df, x="day", y="total_bill", color="sex", barmode="group", title="Total Bill by Day and Sex") fig.show()

The barmode parameter controls how bars from different color groups appear. Use "group" for side-by-side bars, "stack" for stacked bars, and "overlay" for overlapping bars with transparency. When you need a horizontal bar chart, swap x and y or set orientation="h".

If you need a different aggregation such as the mean or median, aggregate the DataFrame first with pandas and then pass the result to bar. For example, use groupby to compute the summary statistic you need. The histfunc parameter in px.histogram is another way to aggregate while plotting.

Scatter Plots with plotly.express.scatter

Scatter plots reveal relationships between two continuous variables. The scatter function maps x and y to the axes, and you can encode additional dimensions with color, size, and symbol. This makes it easy to spot clusters, outliers, or trends.

python
import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", size="petal_length", hover_data=["petal_width"]) fig.show()

The size parameter scales the marker area, which is useful for representing a third numeric variable. hover_data adds extra columns to the tooltip without affecting the visual encoding. For large datasets, consider using opacity to reduce overplotting, or use marginal_x and marginal_y to add histograms along the axes.

When the dataset is very large, the default scatter plot may render thousands of overlapping points, making it hard to read. Plotly Express does not automatically downsample. You can either aggregate the data into bins or switch to a density heatmap using px.density_heatmap if the relationship is better shown as a distribution.

Pie Charts with plotly.express.pie

Pie charts display the proportion of a whole across categories. The pie function takes names for the category labels and values for the numeric sizes. If you omit values, it counts the occurrences of each category.

python
import plotly.express as px df = px.data.tips() fig = px.pie(df, names="day", values="total_bill", title="Share of Total Bill by Day") fig.show()

Pie charts are most effective when you have a small number of categories, typically fewer than six. Too many slices make the chart cluttered and the proportions hard to compare. For more than a few categories, a bar chart is usually a better choice. You can pull a slice out by setting pull to a list of fractions, and you can control the hole size with hole to create a donut chart.

One limitation of pie charts is that they do not handle negative values well. If your data contains negative numbers, the chart will still render but the proportions become misleading. Consider using a bar chart or a stacked bar chart instead.

Histograms with plotly.express.histogram

A histogram shows the distribution of a numeric variable by dividing it into bins and counting the frequency. The histogram function takes a single column as x (or y for horizontal orientation) and automatically computes the bins.

python
import plotly.express as px df = px.data.tips() fig = px.histogram(df, x="total_bill", nbins=30, color="sex", marginal="box", title="Distribution of Total Bill") fig.show()

The nbins parameter controls the number of bins. If you omit it, Plotly uses a default heuristic based on the data range and sample size. You can also set histnorm to "percent" or "density" to normalize the counts. The marginal parameter adds a rug plot, box plot, or violin plot below the histogram to show the raw data points.

When you pass a color column, the histogram splits the data into a separate bar trace for each category. By default, those traces are stacked. You can set barmode="overlay" with opacity to make them transparent and compare distributions side by side. For a cumulative distribution, set cumulative=True.

Histograms are sensitive to bin width. A bin width that is too large hides the shape of the distribution, while one that is too small creates noise. The default nbins often works well, but for publication-quality charts you may need to experiment with it. For finer control over bin edges, update the figure's xbins property with update_traces.

Customizing Layout and Traces

Every Express figure returns a go.Figure object, so you can update any aspect of the layout or traces after creation. Use the update_layout method to set titles, axis labels, font sizes, and margins. Use update_traces to change marker colors, line widths, or hover templates.

python
fig.update_layout( title="Customized Chart", xaxis_title="X Axis", yaxis_title="Y Axis", template="plotly_white", legend_title="Legend" ) fig.update_traces(marker=dict(size=8, line=dict(width=1, color="black")))

The template parameter accepts built-in themes like "plotly", "plotly_white", "seaborn", or "ggplot2". You can also define a custom template if you need consistent branding across multiple charts. The labels parameter in the original Express call provides a convenient way to rename columns for display without modifying the DataFrame.

For web embedding, you can write the figure to an HTML file with fig.write_html(), or convert it to a static image with fig.write_image() if you have the kaleido package installed. The interactive features remain active in the HTML version, which is useful for dashboards or Jupyter notebooks.

Data Handling and Performance Considerations

Plotly Express is a good fit for exploratory datasets with thousands of points. Beyond that, rendering can become sluggish because every point is drawn as a separate SVG or WebGL element. For large datasets, consider aggregating the data before plotting. For example, use pandas groupby to compute summary statistics and then plot the aggregated result.

Another option is to use plotly.graph_objects with scattergl for WebGL rendering, which handles larger point counts better than the standard SVG renderer. However, Express does not expose scattergl directly. If you need to plot millions of points, you should either downsample or switch to a different visualization library designed for big data.

Memory usage is also a consideration. Express figures store the data used for visual channels in the figure object. If your DataFrame has many columns, only the mapped columns are included. You can reduce memory by selecting only the necessary columns before calling the chart function. Additionally, when you save a figure to HTML, the data is embedded as JSON, so a large dataset can produce a very large file. For production dashboards, consider using a server-side rendering approach with Dash or sending only aggregated data to the client.

Finally, Express is designed around pandas DataFrames, which is the recommended input for mapping columns. Some functions also accept plain Python sequences when you pass x and y directly, but a tabular DataFrame is the usual starting point in data analysis workflows.

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.