Plotly in Python: Interactive Charts Guide

Published on: July 10, 2026
Reading time: 5 minutes
Visualização de dados com Plotly em Python

Plotly in Python makes it possible to build charts that readers can explore instead of merely viewing as static images. Users can hover over points, zoom into a region, hide individual series, inspect exact values, and save a chart directly from the browser. These features make Plotly especially useful for data analysis, reports, dashboards, and presentations.

This beginner-friendly guide explains how to install Plotly, create the most common chart types, customize a figure, work with Pandas, and export the result. Basic Python knowledge is enough to follow the examples. Readers who are still learning the language can review our programming logic with Python guide and the overview of Python data structures first.

What is Plotly?

Plotly is a visualization library that generates interactive charts for notebooks, scripts, web pages, and dashboards. The Python package provides two main interfaces:

  • Plotly Express, a concise high-level interface that works particularly well with Pandas DataFrames.
  • Graph Objects, a lower-level interface that offers more detailed control over traces, axes, annotations, and layout.

Both interfaces create the same kind of interactive figure. Plotly handles the browser-side JavaScript automatically, so you do not need to know JavaScript to create a useful visualization. The official Plotly Python documentation contains a gallery of supported charts and detailed API references.

Why use interactive charts?

A static chart answers the questions anticipated by its author. An interactive chart lets the reader investigate additional details. Hover labels show exact values, zooming reveals dense regions, and clickable legends make comparisons easier. This is valuable when presenting sales trends, scientific measurements, geographic information, or model results.

Plotly also integrates naturally with tools covered elsewhere on Academify, including Pandas for tabular data and NumPy for numerical arrays. You can clean the data with Pandas and then pass the resulting columns directly to Plotly.

Install Plotly

Create or activate a Python virtual environment, then install Plotly:

python -m pip install plotly pandas

Using python -m pip helps ensure that the package is installed for the interpreter that runs your script. Test the installation with:

import plotly
print(plotly.__version__)

If the import fails, confirm that the terminal and editor are using the same virtual environment. The Academify guide to configuring VS Code on Windows explains how to select the correct interpreter.

Create a first line chart

Plotly Express can create a complete interactive chart with a few arguments:

import plotly.express as px

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
sales = [15000, 18000, 12000, 22000, 25000, 28000]

fig = px.line(
    x=months,
    y=sales,
    markers=True,
    title="Monthly Sales",
    labels={"x": "Month", "y": "Sales ($)"},
)
fig.show()

fig.show() opens the figure in a suitable renderer, often a browser tab or notebook output cell. Move the pointer over each marker to see its value, drag across the chart to zoom, and double-click to reset the view.

Bar charts for category comparisons

Bar charts are useful when the horizontal axis contains categories rather than continuous time:

products = ["Laptop", "Mouse", "Keyboard", "Monitor", "Webcam"]
units = [45, 120, 85, 60, 95]

fig = px.bar(
    x=products,
    y=units,
    title="Units Sold by Product",
    labels={"x": "Product", "y": "Units"},
    text_auto=True,
)
fig.show()

For horizontal bars, exchange the axes and add orientation="h". Horizontal layouts often work better when category names are long.

Scatter plots and relationships

A scatter plot helps reveal whether two numerical variables move together:

study_hours = [2, 3, 4, 5, 6, 7, 8, 9]
scores = [54, 61, 64, 72, 76, 83, 87, 92]

fig = px.scatter(
    x=study_hours,
    y=scores,
    title="Study Time and Test Scores",
    labels={"x": "Study hours", "y": "Score"},
    trendline="ols",
)
fig.show()

The optional trend line requires the statsmodels package. Without it, remove the trendline argument. A visible relationship does not automatically prove causation, so interpret the pattern within the context of the data.

Work with a Pandas DataFrame

Plotly Express accepts DataFrame column names, which keeps visualization code readable:

import pandas as pd
import plotly.express as px

data = pd.DataFrame({
    "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    "sales": [15000, 18000, 12000, 22000, 25000, 28000],
    "expenses": [8000, 9000, 7500, 11000, 12000, 13000],
})

fig = px.line(
    data,
    x="month",
    y=["sales", "expenses"],
    markers=True,
    title="Sales and Expenses",
)
fig.show()

The official Pandas documentation explains DataFrame selection, cleaning, grouping, and reshaping. Clean column types and missing values before plotting; otherwise, labels can appear in the wrong order or values can be silently omitted.

Use Graph Objects for detailed control

Graph Objects is useful when a figure contains several traces or requires precise customization:

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=months,
    y=[15000, 18000, 12000, 22000, 25000, 28000],
    mode="lines+markers",
    name="Store A",
))
fig.add_trace(go.Scatter(
    x=months,
    y=[12000, 16000, 14000, 19000, 23000, 26000],
    mode="lines+markers",
    name="Store B",
))
fig.update_layout(
    title="Sales Comparison",
    xaxis_title="Month",
    yaxis_title="Sales ($)",
    hovermode="x unified",
)
fig.show()

Each add_trace() call adds one visual series. The unified hover mode displays all values for a selected x-position in one box, which makes comparisons easier.

Customize labels, legends, and annotations

Good visualization is not only about attractive colors. A chart should state what is measured, include units, and make comparisons unambiguous. Use update_layout() for global settings and update_traces() for trace-specific settings:

fig.update_layout(
    title={"text": "Monthly Performance", "x": 0.5},
    legend_title_text="Metric",
    template="plotly_white",
)
fig.update_traces(hovertemplate="%{x}: %{y:,.0f}<extra></extra>")
fig.add_annotation(
    x="Apr",
    y=22000,
    text="Campaign launched",
    showarrow=True,
)

Avoid adding unnecessary decoration. Strong contrast, descriptive labels, and a restrained number of series usually communicate more effectively than a crowded chart.

Save charts as HTML or images

Save a self-contained interactive page with:

fig.write_html("sales_chart.html")

The HTML file opens in a normal browser and preserves zooming, hover labels, and legend controls. For static PNG, SVG, or PDF output, install Kaleido and call write_image():

python -m pip install kaleido
fig.write_image("sales_chart.png", width=1200, height=700, scale=2)

Static output is convenient for documents and slides, while HTML is better when exploration matters.

Common beginner mistakes

  • Columns have the wrong type: convert numeric text with pd.to_numeric() and parse dates before plotting.
  • Categories appear in an unexpected order: define an explicit category order or sort the DataFrame.
  • The chart is unreadable: reduce the number of traces, aggregate the data, or split the analysis into multiple figures.
  • Images will not export: verify that Kaleido is installed in the same environment as Plotly.
  • The script opens no visible chart: try saving to HTML and opening the file, especially on remote servers without a graphical desktop.

When to choose Plotly

Choose Plotly when readers benefit from hover details, zooming, filters, or browser-based sharing. For publication-quality static figures with highly specialized control, Matplotlib may be more appropriate. In many projects both libraries coexist: Matplotlib produces static assets, while Plotly powers exploratory analysis and dashboards.

Conclusion

Plotly turns Python data into interactive visual explanations. Start with Plotly Express for line, bar, and scatter charts, then move to Graph Objects when you need multiple traces or detailed layout control. Combine it with Pandas, validate the data before plotting, and choose an export format that matches how the audience will use the result.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    logos do Python, Pandas e NumPy numa mesa de madeira
    Data Science
    Foto de perfil de Leandro Hirt da Academify

    Python Data Analysis with Pandas and NumPy

    Learn Python data analysis with NumPy and Pandas: arrays, DataFrames, cleaning, filtering, summaries, grouping, missing data, and a complete workflow.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    representação de IA com código binário na tela
    Data Science
    Foto de perfil de Leandro Hirt da Academify

    Scikit-Learn: Machine Learning for Beginners

    Learn Scikit-Learn step by step: prepare data, split datasets, train classification and regression models, evaluate results, use pipelines, tune parameters,

    Ler mais

    Tempo de leitura: 7 minutos
    10/07/2026
    Logo do matplotlib em um fundo branco
    Data Science
    Foto de perfil de Leandro Hirt da Academify

    Matplotlib in Python: Beginner Chart Guide

    Learn Matplotlib in Python from installation to line, bar, scatter and pie charts, labels, legends, subplots, Pandas integration, and image

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Mesa de trabalho com laptop exibindo gráficos e a logo do Pandas em primeiro plano
    Data Science
    Foto de perfil de Leandro Hirt da Academify

    Pandas in Python: Complete Beginner Guide

    Learn Pandas in Python from scratch: Series, DataFrames, CSV and Excel import, selection, filtering, missing values, grouping, merging, export, and

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Geração e edição de planilhas Excel usando Python
    Data Science
    Foto de perfil de Leandro Hirt da Academify

    Generate and Edit Excel Files with Python

    Learn how to generate and edit Excel files with Python using Pandas and Openpyxl: create spreadsheets, read data, add formulas,

    Ler mais

    Tempo de leitura: 4 minutos
    03/06/2026
    Limpeza de dados sujos em Python para data cleaning
    Data Science
    Foto de perfil de Leandro Hirt da Academify

    Clean Messy Data in Python: Practical Guide

    Learn how to clean messy data in Python with Pandas, missing values, duplicates, type conversion, text cleanup, outliers, and reusable

    Ler mais

    Tempo de leitura: 9 minutos
    19/05/2026