Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Altair
  • Matplotlib
  • Pandas
  • Seaborn
  • Ggplot
  • Plotly
  • Bokeh
  • Networkx
  • Machine Learning Math
  • Machin Learning
  • Data Analysis
  • Deep Learning
  • Deep Learning Projects
  • NLP
  • Computer vision
  • Data science
  • Machin Learning Interview question
  • Deep learning interview question
Open In App
Next Article:
Horizontal Stripplot with Jitter using Altair in Python
Next article icon

Scatter Plot with Regression Line using Altair in Python

Last Updated : 24 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite: Altair

In this article, we are going to discuss how to plot to scatter plots with a regression line using the Altair library.

Scatter Plot and Regression Line

  • The values of two different numeric variables is represented by dots or circle in Scatter Plot. Scatter Plot is also known as aka scatter chart or scatter graph. The position of each dot in the horizontal and vertical axis indicates a value for an individual data point.
  • Scatter plots are beneficial to observe the relationship between the variables.
  • Regression Line is the straight line that best fits the data so that the overall distance from the line to the points plotted on the chart is the smallest.

Installation:

To install the Altair library, write the below command on your command prompt.

pip install altair

In this article for datasets, we are using the vega_datasets package, to install write the below command on your command prompt.

pip install vega_datasets

Approach:

  • Import the necessary libraries.
  • Create or load the dataset from the vega_dataset package.
  • To plot the scatter plot using Altair library, we have to give three important elements to plot as follows.
    • In the first element altair.Chart(dataset) pass the dataset as the parameter.
    • In the second element with a dot (.) add mark_point() this element specifies the type of chart we are plotting.
    • In the third element with a dot (.) add encode() in which pass the columns between which we are plotting the scatter plot.
  • Store this scatter plot in a variable named “fig”.
  • Then plot the regression line transform_regression() function and pass the columns as a parameter on which regression line is plotted and add this to the scatter plot which is stored in “fig” variable.
  • Store the scatter plot with regression line in variable let be named as "final_plot".
  • In case written the program code in python file use save() function to save the plot and you can view that plot on Chrome browser by using CTRL+O command then open the saved plot to visualize.
  • Otherwise, if written in Jupyter notebook or notebook environment use show() to visualize the plot.
  • To know how to use Jupyter Notebook: Getting started with Jupyter Notebook.
  • For better understanding, let's do some examples by using airports and seattle_weather dataset that comes with the Vega dataset package.

Example 1: Default Scatter plot with Regression line on airports dataset.

Python
# importing libraries import altair as alt from vega_datasets import data  # importing airports dataset from  # vega_datasets package airport = data.airports()  # making the scatter plot on latitude and longitude fig = alt.Chart(airport).mark_point().encode(x='latitude',y='longitude')  # making the regression line using transform_regression  # function and add with the scatter plot final_plot = fig + fig.transform_regression('latitude','longitude').mark_line()  # saving the scatter plot with regression line final_plot.save('output1.html') 

Output:

Example 2: Scatter Plot with Regression Line by setting up the color using airport dataset.

Python
# importing libraries import altair as alt from vega_datasets import data  # importing airports dataset from vega_datasets package airport = data.airports()  # making the scatter plot on latitude and longitude # setting color on the basis of country fig = alt.Chart(airport).mark_point().encode(   x='latitude',y='longitude',color='country')  # making the regression line using transform_regression # function and add with the scatter plot final_plot = fig + fig.transform_regression('latitude','longitude').mark_line()  # saving the scatter plot with regression line final_plot.save('output2.html') 

Output:

Example 3: Default Scatter Plot with Regression Line using seattle_weather dataset.

Python
# importing libraries import altair as alt from vega_datasets import data  # importing weather dataset from vega_datasets package weather_data = data.seattle_weather()  # making the scatter plot on temp_max and temp_min fig = alt.Chart(weather_data).mark_point().encode(x='temp_max',y='temp_min')  # making the regression line using transform_regression # function and add with the scatter plot final_plot = fig + fig.transform_regression('temp_max','temp_min').mark_line()  # saving the scatter plot with regression line final_plot.save('output3.html') 

Output:

Example 4: Scatter Plot with Regression Line by setting up color using seattle_weather dataset.

Python
# importing libraries import altair as alt from vega_datasets import data  # importing weather dataset from vega_datasets package weather_data = data.seattle_weather()  # making the scatter on temp_max and temp_min fig = alt.Chart(weather_data).mark_point().encode(   x='temp_max',y='temp_min',color='weather')  # making the regression line using transform_regression # function and add with the scatter plot final_plot = fig + fig.transform_regression('temp_max','temp_min').mark_line()  # saving the scatter plot with regression line final_plot.save('output4.html') 

Output:


Next Article
Horizontal Stripplot with Jitter using Altair in Python
author
srishivansh5404
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Technical Scripter 2020
  • Python-Altair
Practice Tags :
  • python

Similar Reads

  • Introduction to Altair in Python
    Altair is a statistical visualization library in Python. It is a declarative in nature and is based on Vega and Vega-Lite visualization grammars. It is fast becoming the first choice of people looking for a quick and efficient way to visualize datasets. If you have used imperative visualization libr
    5 min read
  • Create Grouped Bar Chart using Altair in Python
    Grouped bar charts are a handy tool to represent our data when we want to compare multiple sets of data items one against another. To make a grouped bar chart, we require at least three rows of three columns of data in our dataset. The three columns can be used as- one for values, one for series, an
    3 min read
  • Scatter Plot with Regression Line using Altair in Python
    Prerequisite: Altair In this article, we are going to discuss how to plot to scatter plots with a regression line using the Altair library. Scatter Plot and Regression Line The values of two different numeric variables is represented by dots or circle in Scatter Plot. Scatter Plot is also known as a
    4 min read
  • Horizontal Stripplot with Jitter using Altair in Python
    Prerequisites: Altair Altair is a statistical data visualization library in python which is based on Vega and Vega-Lite visualization grammars. A Stripplot is used for graphical data analysis.  It is a simple plot of response values in a sorted order along a single axis. The strip plot consists of 2
    2 min read
  • How To Make Stripplot with Jitter in Altair Python?
    Prerequisites: Altair Altair is a statistical data visualization library in python which is based on Vega and Vega-Lite visualization grammars. A Stripplot is used for graphical data analysis.  It is a simple plot of response values in a sorted order along a single axis. The strip plot consists of 2
    3 min read
  • How To Facet a Scatter Plot with Altair?
    In this article, we will learn how to Facet a Scatter Plot with Altair. Let's recall some concepts : Altair is a statistical visualization library in Python. It is declarative in nature and is based on Vega and Vega-Lite visualization grammars. It is fast becoming the first choice of people looking
    3 min read
  • How to Make a Simple Histogram with Altair in Python?
    Prerequisites: Altair Simple Histogram is the representation of frequency distribution by means of rectangles whose width represents the class interval. Histogram is the graphical representation that organizes grouped data points into the specified range. By using histogram we can visualize large am
    4 min read
  • Area Chart with Altair in Python
    Prerequisite: Introduction to Altair in Python An Area Graph shows the change in a quantitative quantity with respect to some other variable. It is simply a line chart where the area under the curve is colored/shaded. It is best used to visualize trends over a period of time, where you want to see h
    2 min read
  • How to Make Overlapping Histograms in Python with Altair?
    Prerequisite: Altair A histogram represents data provided during a sort of some groups. It is an accurate method for the graphical representation of numerical data distribution. It is a kind of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. Us
    2 min read
  • Python Altair - Scatter Plot
    In this article, we will learn a Simple Scatter plot with Altair using python. Altair is one of the latest interactive data visualizations library in python. Altair is based on vega and vegalite- A grammar of interactive graphics.  Here we will import the Altair library for using it. And then we wil
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences