The Wayback Machine - https://web.archive.org/web/20240907031312/https://www.geeksforgeeks.org/data-visualization-using-plotnine-and-ggplot2-in-python/
Open In App

Data Visualization using Plotnine and ggplot2 in Python

Last Updated : 29 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Data Visualization is the technique of presenting data in the form of graphs, charts, or plots. Visualizing data makes it easier for the data analysts to analyze the trends or patterns that may be present in the data as it summarizes the huge amount of data in a simple and easy-to-understand format. 

In this article, we will discuss how to visualize data using plotnine in Python which is a strict implementation of the grammar of graphics. Before starting let’s understand a brief about what is the grammar of graphics.

What is the Grammar of Graphics?

A grammar of graphics is basically a tool that enables us to describe the components of a given graphic. Basically, this allows us to see beyond the named graphics, (scatter plot, to name one) and to basically see the underlying statistics behind it. Consider grammar of graphics as the grammar of English where we use different words, tenses, punctuations to form a sentence. 

Components of Grammar of graphics

Typically, to build or describe any visualization with one or more dimensions, we can use the components shown in the below image. 

Components of Grammar of graphics

First, we will see the three main components that are required to create a plot, and without these components, the plotnine would not be able to plot the graph. These are- 

  • Data is the dataset that is used for plotting the plot.
  • Aesthetics (aes) is the mapping between the data variables and the variables used by the plot such as x-axis, y-axis, color, fill, size, labels, alpha, shape, line width, line type.
  • Geometric Objects (geoms) is the type of plot or a geometric object that we want to use such as point, line, histogram, bar, boxplot, etc.

There are various optional components that can make the plot more meaningful and presentable. These are –

  • Facets allow the data to be divided into groups and each group is plotted separately.
  • Statistical transformations compute the data before plotting it.
  • Coordinates define the position of the object in a 2D plane.
  • Themes define the presentation of the data such as font, color, etc.

Installation

The plotnine is based on ggplot2 in R Programming language which is used to implement grammar of graphics in Python. To install plotnine type the below command in the terminal.

pip install plotnine

python install plotninepython install plotnine

Plotting Data using Plotnine and ggplot in Python

Here we will use the three main components i.e. data, aesthetics, and geometric objects for plotting our data. Let’s go through each component in detail.

Data

The data is the dataset which is needed to be plotted. We can specify the data using the ggplot constructor and passing the dataset to that constructor.

Example: Specifying dataset for the ggplot

We will use the Iris dataset and will read it using Pandas.

Python3




import pandas as pd
from plotnine import ggplot
  
# reading dataset
df = pandas.read_csv("Iris.csv")
  
# passing the data to the ggplot 
# constructor
ggplot(df)


Output:

Specifying dataset for the ggplot

This will give us a blank output as we have not specified the other two main components.

Aesthetics

Now let’s define the variable that we want to use for each axis in the plot. Aesthetics maps data variables to graphical attributes, like 2D position and color.

Example: Defining aesthetics of the plotnine and ggplot in Python

Python3




import pandas as pd
from plotnine import ggplot, aes
  
# reading dataset
df = pd.read_csv("Iris.csv")
  
ggplot(df) + aes(x="Species", y="SepalLengthCm")


Output:

Defining aesthetics of the plotnine and ggplot in Python

In the above example, we can see that Species is shown on the x-axis and sepal length is shown on the y-axis. But still there is no figure in the plot. This can be added using geometric objects.

Geometric Objects

After defining the data and the aesthetics we need to define the type of plot that we want for visualization. This tells the plotline that how the data points should be shown. It provides a variety of geometric objects like scatter plots, line charts, bar charts, box plots, etc. Let’s see a variety of them and how to use them.

Note: For the list of all the geoms refer to the plotnine’s geom API reference.

Example 1: Adding geometric objects to the plotnine and ggplot in Python

Python3




import pandas as pd
from plotnine import ggplot, aes, geom_col
  
# reading dataset
df = pd.read_csv("Iris.csv")
  
ggplot(df) + aes(x="Species", y="SepalLengthCm") + geom_col()


Output:

Adding geometric objects to the plotnine and ggplot in Python

In the above example, we have used the geam_col() geom that is a bar plot with the base on the x-axis. We can change this to different types of geoms that we find suitable for our plot.

Example 2: Plotting Histogram with plotnine and ggplot in Python

Python3




import pandas as pd
from plotnine import ggplot, aes, geom_histogram
  
# reading dataset
df = pd.read_csv("Iris.csv")
  
ggplot(df) + aes(x="SepalLengthCm") + geom_histogram()


Output:

Plotting Histogram with plotnine and ggplot in Python

Example 3: Plotting Scatter plot with plotnine and ggplot in Python

Python3




import pandas as pd
from plotnine import ggplot, aes, geom_point
  
# reading dataset
df = pd.read_csv("Iris.csv")
  
ggplot(df) + aes(x="Species", y="SepalLengthCm") + geom_point()


Output:

Plotting Scatter plot with plotnine and ggplot in Python

Example 4: Plotting Box plot with plotnine and ggplot in Python

Python3




import pandas as pd
from plotnine import ggplot, aes, geom_boxplot
  
# reading dataset
df = pd.read_csv("Iris.csv")
  
# passing the data to the ggplot 
# constructor
ggplot(df) + aes(x="Species", y="SepalLengthCm") + geom_boxplot()


Output:

Plotting Box plot with plotnine and ggplot in Python

Example 5: Plottin Line chart with plotnine and ggplot in Python

Python3




import pandas as pd
from plotnine import ggplot, aes, geom_line
  
# reading dataset
df = pd.read_csv("Iris.csv")
  
ggplot(df) + aes(x="Species", y="SepalLengthCm") + geom_line()


Output:

Plottin Line chart with plotnine and ggplot in Python

Till now we have learnt about how to create a basic chart using the concept of grammar of graphics and it’s three main components. Now let’s learn how to customize these charts using the other optional components.

Enhacing Data visualizations using plotnine and ggplot

 Here we will learn about the remaining optional components. These components are – 

  • Facets
  • Statistical transformations
  • Coordinates
  • Themes 

Facets

Facets are used to plot subsets of data. it allows an individual plot for groups of data in the same image.

For example, let’s consider the tips dataset that contains information about people who probably had food at a restaurant and whether or not they left a tip, their age, gender and so on. Lets have a look at it.

Note: To download the dataset used, click here.

tips dataset

Now let’s suppose we want to plot about what was the total bill according to the gender and on each day. In such cases facets can be very useful, let’s see how.

Example: Facets with plotnine and ggplot in Python 

Python3




import pandas as pd
from plotnine import ggplot, aes, facet_grid, labs, geom_col
  
# reading dataset
df = pd.read_csv("tips.csv")
  
(
    ggplot(df)
    + facet_grid(facets="~sex")
    + aes(x="day", y="total_bill")
    + labs(
        x="day",
        y="total_bill",
    )
    + geom_col()
)


Output:

Facets with plotnine and ggplot in Python

Statistical transformations

Statistical transformations means computing data before plotting it. It can be seen in the case of a histogram. Now let’s consider the above example, where we wanted to find the measurement of the sepal length column and now we want to distribute that measurement into 15 columns. The geom_histogram() function of the plotnine computes and plot this data automatically.

Example: Statistical transformations using plotnine and ggplot in Python

Python3




import pandas as pd
from plotnine import ggplot, aes, geom_histogram
  
# reading dataset
df = pd.read_csv("Iris.csv")
  
ggplot(df) + aes(x="SepalLengthCm") + geom_histogram(bins=15)


Output:

Statistical transformations using plotnine and ggplot in Python

Coordinates

The coordinates system defines the imappinof the data point with the 2D graphical location on the plot. Let’s see the above example of histogram, we want to plot this histogram horizontally. We can simply do this by using the coord_flip() function.

Example: Coordinate system in plotnine and ggplot in Python

Python3




import pandas as pd
from plotnine import ggplot, aes, geom_histogram, coord_flip
  
# reading dataset
df = pd.read_csv("Iris.csv")
  
(
    ggplot(df)
    + aes(x="SepalLengthCm")
    + geom_histogram(bins=15)
    + coord_flip()
)


Output:

Coordinate system in plotnine and ggplot in Python

Themes

Themes are used for improving the looks of the data visualization. Plotnine includes a lot of theme which can be found in the plotnine’s themes API. Let’s use the above example with facets and try to make the visualization more interactive.

Example: Themes in plotnine and ggplot in Python

Python3




import pandas as pd
from plotnine import ggplot, aes, facet_grid, labs, geom_col, theme_xkcd
  
# reading dataset
df = pd.read_csv("tips.csv")
  
(
    ggplot(df)
    + facet_grid(facets="~sex")
    + aes(x="day", y="total_bill")
    + labs(
        x="day",
        y="total_bill",
    )
    + geom_col()
    + theme_xkcd()
)


Output:

Themes in plotnine and ggplot in Python

We can also fill the color according to add more information to this graph. We can add color for the time variable in the above graph using the fill parameter of the aes function.

Plotting Multidimensional Data

Till now we have seen how to plot more than 2 variables in the case of facets. Now let’s suppose we want to plot data using four variables, doing this with facets can be a little bit of hectic, but with using the color we can plot 4 variables in the same plot only. We can fill the color using the fill parameter of the aes() function.

Example: Adding color to plotnine and ggplot in Python

Python3




import pandas as pd
from plotnine import ggplot, aes, facet_grid, labs, geom_col, theme_xkcd
  
# reading dataset
df = pd.read_csv("tips.csv")
  
(
    ggplot(df)
    + facet_grid(facets="~sex")
    + aes(x="day", y="total_bill", fill="time")
    + labs(
        x="day",
        y="total_bill",
    )
    + geom_col()
    + theme_xkcd()
)


Output:

Adding color to plotnine and ggplot in Python

Saving the Plot

We can simply save the plot using the save() method. This method will esport the plot as an image.

Example: Saving the plotnine and ggplot in Python

Python3




import pandas as pd
from plotnine import ggplot, aes, facet_grid, labs, geom_col, theme_xkcd
  
# reading dataset
df = pd.read_csv("tips.csv")
  
plot = (
    ggplot(df)
    + facet_grid(facets="~sex")
    + aes(x="day", y="total_bill", fill="time")
    + labs(
        x="day",
        y="total_bill",
    )
    + geom_col()
    + theme_xkcd()
)
  
plot.save("gfg plotnine tutorial.png")


Output:

Saving the plotnine and ggplot in Python



Previous Article
Next Article

Similar Reads

How to Save Time with Data Visualization using Stack in R with ggplot2
The widely used R package ggplot2 is used to produce beautiful and efficient data visualisations. Here are some pointers for speeding up data visualisation using the "stack" feature of ggplot2: Select the pertinent information: Make sure the data you plan to use in your visualisation is appropriate. You will need data that contains information on e
6 min read
Master Data Visualization With ggplot2
In this article, we are going to see the master data visualization with ggplot2 in R Programming Language. Generally, data visualization is the pictorial representation of a dataset in a visual format like charts, plots, etc. These are the important graphs in data visualization with ggplot2, Bar ChartViolin PlotsDensity PlotsBox PlotsPie ChartStack
8 min read
Conditional Data Visualization Using Google Data Studio
In this article, we will learn how to do Conditional Data Visualization using Google Data studio. Before moving forward, let's understand the title itself. Data visualization Data visualization is all about getting useful insights from the data through graphical media or visuals. When data is presented in a visual format. It becomes easy and quick
3 min read
Difference Between Data Mining and Data Visualization
Data mining: Data mining is the method of analyzing expansive sums of data in an exertion to discover relationships, designs, and insights. These designs, concurring to Witten and Eibemust be "meaningful in that they lead to a few advantages, more often than not a financial advantage." Data in data mining is additionally ordinarily quantitative par
2 min read
Difference Between Data Visualization and Data Analytics
Data Visualization: Data visualization is the graphical representation of information and data in a pictorial or graphical format(Example: charts, graphs, and maps). Data visualization tools provide an accessible way to see and understand trends, patterns in data and outliers. Data visualization tools and technologies are essential to analyze massi
3 min read
Difference Between Data Science and Data Visualization
Data Science: Data science is study of data. It involves developing methods of recording, storing, and analyzing data to extract useful information. The goal of data science is to gain knowledge from any type of data both structured and unstructured. Data science is a term for set of fields that are focused on mining big data sets and discovering t
2 min read
Stock Data Analysis and Data Visualization with Quantmod in R
Analysis of historical stock price and volume data is done in order to obtain knowledge, make wise decisions, and create trading or investment strategies. The following elements are frequently included in the examination of stock data in the R Programming Language. Historical Price Data: Historical price data contains information about a stock's op
8 min read
Visualization and Prediction of Crop Production data using Python
Prerequisite: Data Visualization in Python Visualization is seeing the data along various dimensions. In python, we can visualize the data using various plots available in different modules. In this article, we are going to visualize and predict the crop production data for different years using various illustrations and python libraries. Dataset T
4 min read
Why Data Visualization Matters in Data Analytics?
What if you wanted to know the number of movies produced in the world per year in different countries? You could always read this data in the form of a black and white text written on multiple pages. Or you could have a colorful bar chart that would immediately tell you which countries are producing more movies and if the total movies per year are
7 min read
Why is Data Visualization so Important in Data Science
Would you prefer to view large data tables and then make sense of that data or view a data visualization that represents that data in an easy-to-understand visual format? Well, most of you would prefer data visualization! That is because data visualization is extremely useful in understanding the data and obtaining useful insights. It can allow you
8 min read
COVID-19 Data Visualization using matplotlib in Python
It feels surreal to imagine how the virus began to spread from one person that is patient zero to four million today. It was possible because of the transport system. Earlier back in the days, we didn’t have a fraction of the transportation system we have today. Well, what good practices you can follow for now is to sanitize your grocery products a
8 min read
Python - Data visualization using covid19 India API
API (Application Programming Interface) is a computing interface that interacts between multiple software. JSON (JavaScript Object Notation) is a lightweight format for storing and transporting data. It is used to send data from server to web. Required modules: matplotlibrequestspandasjson Commands to install modules: pip install matplotlib pip ins
5 min read
Using Plotly for Interactive Data Visualization in Python
Plotly is an open-source module of Python which is used for data visualization and supports various graphs like line charts, scatter plots, bar charts, histograms, area plot, etc. In this article, we will see how to plot a basic chart with plotly and also how to make a plot interactive. But before starting you might be wondering why there is a need
13 min read
Python - Data visualization using Bokeh
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots. Bokeh output can be obtained in various mediums like notebook, html and server. It is possible to embed bokeh plots in Django and flask apps. Bokeh provides two visualization interfaces to users: bokeh.models : A low level interface that pro
3 min read
Data Visualization using Turicreate in Python
In Machine Learning, Data Visualization is a very important phase. In order to correctly understand the behavior and features of your data one needs to visualize it perfectly. So here I am with my post on how to efficiently and at the same time easily visualize your data to extract most out of it. Before going in detail about how to visualize data
3 min read
Data Visualization Using Bqplot in Python
Bqplot is a powerful and flexible tool for creating interactive visualizations within Jupyter Notebooks. Its integration with ipywidgets and use of D3.js make it a valuable library for data scientists and developers who need to build interactive data visualization applications. What is BqPlot in Python?BqPlot is a fun tool that helps you make cool
9 min read
Data Visualization using Matplotlib in Python
Data visualization is a crucial aspect of data analysis, enabling data scientists and analysts to present complex data in a more understandable and insightful manner. One of the most popular libraries for data visualization in Python is Matplotlib. In this article, we will provide a comprehensive guide to using Matplotlib for creating various types
15+ min read
Interactive Data Visualization with Python and Bokeh
In this article, we'll learn how to do Interactive Data Visualization with Bokeh. Bokeh is a Python library that is used for creating interactive visualizations for modern web browsers. It handles custom or specialized use cases very simply. It provides high-performance interactive charts and plots. Bokeh output can be obtained in various mediums l
8 min read
Data analysis and Visualization with Python
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. In this article, I have used Pandas to analyze data on Country Data.csv file from UN public Data Sets of a popular 'statweb.stanford.ed
4 min read
Data Visualisation using ggplot2(Scatter Plots)
The correlation Scatter Plot is a crucial tool in data visualization and helps to identify the relationship between two continuous variables. In this article, we will discuss how to create a Correlation Scatter Plot using ggplot2 in R. The ggplot2 library is a popular library used for creating beautiful and informative data visualizations in R Prog
7 min read
Data Visualization using GoogleVis Package
GoogleVis is a package in R that is used to act as an interface between R and the Google API to produce interactive charts which can be easily embedded into web pages. This package helps the user to plot the data without uploading them into google. In this article let's parse through some charts that can be plotted using googleVis in R Programming
5 min read
Interactive visualization of data using Bokeh
Bokeh is a Python library for creating interactive data visualizations in a web browser. It offers human-readable and fast presentation of data in an visually pleasing manner. If you’ve worked with visualization in Python before, it’s likely that you have used matplotlib. But Bokeh differs from matplotlib. To install Bokeh type the below command in
4 min read
Data Visualization using ggvis Package in R
The ggvis is an interactive visualization package in R language that is based on the popular ggplot2 package. It allows you to create interactive plots and graphics that can be explored and manipulated by the user. ggvis supports a wide range of plot types including scatter plots, line charts, bar charts, histograms, and more. One of the key featur
15+ min read
Weather Data Visualization using R
Visualizing weather data is essential for understanding trends, patterns, and anomalies in meteorological information. R, with its robust packages for data manipulation and visualization, offers powerful tools to create insightful weather data visualizations. This article will guide you through the process of visualizing weather data in R, covering
5 min read
Animated Data Visualization using Plotly Express
Data Visualization is a big thing in the data science industry and displaying the proper statistics to a business or governments can help them immeasurably in improving their services. It is very painful to understand data from different times from multiple charts and make any sense of it. That is where the need for animated data visualizations lie
4 min read
Data Visualization with Python
In today's world, a lot of data is being generated on a daily basis. And sometimes to analyze this data for certain trends, patterns may become difficult if the data is in its raw format. To overcome this data visualization comes into play. Data visualization provides a good, organized pictorial representation of the data which makes it easier to u
14 min read
Exploring 3D Data Visualization with Mayavi in Python
Mayavi is an interactive 3D plotting library that can be used to visualize complex spatial datasets. Although matplotlib can also be used for simple 3D plotting, Mayavi uses a more complex engine (VTK), making Mayavi more suitable for displaying large and complex data. The Mayavi library is like a magic tool that helps us do lots of cool things in
7 min read
Advanced 3D Spectroscopic Data Visualization with Python
Spectroscopic data typically consists of measurements taken at various wavelengths or frequencies. These measurements can be used to identify materials, analyze chemical compositions, and study physical properties. The data is often represented in a tabular format, where each row corresponds to a different sample or measurement, and each column rep
5 min read
Introduction to VisPy: Mastering High-Performance 2D/3D Data Visualization in Python
VisPy is a high-performance interactive 2D/3D data visualization library in Python. It offers an interface for high-quality visualization and manipulation of large data sets in 2D/3D. Leaning on the power of the GPU, it provides both efficient and interactive visualizations. VisPy leverages the computational power of modern Graphics Processing Unit
9 min read
Data Visualization with Seaborn - Python
Data Visualization is the presentation of data in pictorial format. It is extremely important for Data Analysis, primarily because of the fantastic ecosystem of data-centric Python packages. And it helps to understand the data, however, complex it is, the significance of data by summarizing and presenting a huge amount of data in a simple and easy-
15 min read