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
  • Data Visualization
  • Statistics in R
  • Machine Learning in R
  • Data Science in R
  • Packages in R
  • Data Types
  • String
  • Array
  • Vector
  • Lists
  • Matrices
  • Oops in R
Open In App
Next Article:
How to Create Grouped Line Chart Using ggplot and plotly in R
Next article icon

How to Create Pie Chart Using Plotly in R

Last Updated : 31 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The pie chart is a circular graphical representation of data that is divided into some slices based on the proportion of it present in the dataset. 

In R programming this pie chart can be drawn using Plot_ly() function which is present in the Plotly package. In this article, we are going to plot a pie chart for the default dataset iris which is present in CRAN Repository. In Plotly the pie chart can be plotted in different ways simple, styled, and donut chart.

Loading Libraries

As we require the Plotly library, we can install and load it with the given command.

R
# Install required package(plotly) install.packages("plotly")  # Load the installed package into current working environment library(plotly) 

Loading Dataset

Here, we are using Iris Dataset, so we need to load it. For that run the code below.

R
# Load the dataset data(iris)  # Convert the dataset into a data frame df<-data.frame(iris) 


Once we have the dataset, we can now plot the pie chart. Let's start with the Simple pie chart.

Simple Pie Chart 

Syntax : plot_ly(df,type,marker,labels,values) %>% layout()

where,

  • df - data frame
  • type - used to specify the type of plot we want to visualize
  • marker() - function used to set marker genotype objects 
  • labels - names of categorical variables in the dataset
  • values - values of the columns in the dataset that we want to plot are specified here (optional)
  • layout() -  this function is used to change the layout as required (like assigning a title to the plot...)
R
library(dplyr)  Pie_Data<-count(iris,Species)  # Plotting the piechart using plot_ly() function plotly::plot_ly(data=Pie_Data,values=~n,labels=~factor(Species),                 marker=list(colors=c("green","orange","blue")),                 type="pie") %>% layout(title="Species Percentage of Iris Dataset") 

Output:

pie chart using plotly in RGeeksforgeeks
pie chart using Plotly in R
  • Pie_Data - count(iris, Species): This line counts the number of times each distinct value appears in the Species column of the iris dataset using the count() function from the dplyr package. It produces a brand-new data frame with the name Pie_Data and two columns: Species and n, where n denotes the total number of species.
     
  • plotly::plot_ly(...): Using the plot_ly() function from the Plotly package, this line generates a pie chart. The input data is the Pie_Data data frame.
     
  • data = Pie_Data: This specifies the data frame for the plot's input data.
     
  • values = "n," labels = "factor(Species")": This sets the pie chart's values to the Pie_Data's n column and its labels to that column. The variables are to be indicated by the symbol.
     
  • Sets the colors for the pie chart sectors using marker = list(colors = c("green", "orange", "blue")). A vector of strings representing the color names is used to specify the colors.
     
  • Specifies the chart type as a pie chart with type = "pie".%>%: The various function calls are chained together using the pipe operator (%>%).
    The layout() function sets the chart's title to "Species Percentage of Iris Dataset" by substituting "title" for "Species Percentage of Iris Dataset".
     

Styled Pie chart 

Here we will add the colors, text-info, text-position, etc. to the pie chart.

R
# Plotting the styled pie chart using plot_ly() function plotly::plot_ly(data=Pie_Data,values=~n,labels=~factor(Species),                 textposition="outside",textinfo = 'label+percent',                 hoverinfo='label',outsidetextfont = list(color = 'red'),                 marker=list(colors=c("grey", 'blue', 'yellow'),                 line=list(color="white",width=2)),type="pie") %>%                 layout(title="Species Percentage of Iris Dataset") 

Output:

pie chart using plotly in RGeeksforgeeks
pie chart using Plotly in R

Donut Chart 

In the Donut pie chart, we need to mention the hole value. 

R
plotly::plot_ly(Pie_Data)%>%   add_pie(Pie_Data,labels=~factor(Species),values=~n,           textinfo="label+percent",type='pie',hole=0.6)%>%   layout(title="Donut Plot Using R") 

Output:

Donut chart using Plotly in RGeeksforgeeks
Donut chart using Plotly in R

Custimiozation of Donut charts

We can increase or decrease the circle rediuas by changing hole size of the donut to make more attractive.

R
plotly::plot_ly(Pie_Data)%>%   add_pie(Pie_Data,labels=~factor(Species),values=~n,           textinfo="label+percent",type='pie',hole=0.3)%>%   layout(title="Donut Plot Using R") 

Output:

Donut chart using Plotly in RGeeksforgeeks
Donut chart using Plotly in R

Next Article
How to Create Grouped Line Chart Using ggplot and plotly in R

S

sri06harsha
Improve
Article Tags :
  • Technical Scripter
  • R Language
  • Technical Scripter 2022

Similar Reads

  • How to Create Grouped Line Chart Using ggplot and plotly in R
    Creating grouped line charts in R allows you to visualize multiple trends or series in the same plot. By using the combination of ggplot2 plotting and plotly for interactivity, you can create rich, dynamic visualizations that let you explore your data in depth. In this article, we will explore how t
    4 min read
  • How to Create an Animated Line Graph using Plotly
    An animated line graph is a visual representation of data that changes over time or over a categorical variable. It can be a powerful tool for visualizing trends and patterns in data and can help to communicate complex ideas in a clear and concise way. In this tutorial, we will learn how to create a
    5 min read
  • How to create a scatter plot using lattice package in R?
    In this article, we will discuss how to create the scatter plots using lattice package in R programming language. In R programming, the Lattice package is a data visualization library that consists of various functions to plot different kinds of plots. Using the lattice library we can able to plot v
    2 min read
  • How to plot a graph in R using CSV file ?
    To plot a graph in R using a CSV file, we need a CSV file with two-column, the values in the first column will be considered as the points at the x-axis and the values in the second column will be considered as the points at the y-axis. In this article, we will be looking at the way to plot a graph
    2 min read
  • How to create stacked bar chart using ggvis in R
    In this article, we will be looking at the approach for creating a stacked bar chart using ggvis in the R programming language. Create the stacked bar chart with the layer_bars function of ggvis package In this approach to create the stacked bar chart with layer_bars function from the ggvis package,
    3 min read
  • Create a Choropleth Map by using Plotly Package in R
    There are plenty of packages in R that can be used to make maps, like leaflet, mapview, ggplot, spplot, plotly, etc. Each of the packages has its own advantages and disadvantages. But all of them have the common goal of making it easy to create maps and visualize geospatial data. In this article, we
    4 min read
  • How to Customize the Modebar in Plotly Using R?
    Plotly is a library for creating interactive graphs and visualizations. The modebar provides tools for zooming, downloading, and resetting the graph. Customizing the modebar can improve usability and make visualizations more suited to your needs. In this article, we'll explore how to customize the m
    3 min read
  • How to Create Radar Charts in R?
    In this article, we are going to see how to create Radar Charts in R Programming Language. Radar charts are also known as Spider or Web or Polar charts. It is a graphical graph to display multivariate data in form of 2D charts of three or more quantitative variables which are represented on axes sta
    4 min read
  • Interactive Charts using Plotly in R
    R Programming Language is a powerful tool for data analysis and visualization. Interactive plots with R can be particularly useful for exploring and presenting data, but creating them can be challenging. The Shiny package provides a framework for creating web-based applications with R, including int
    5 min read
  • How to Make Lines of Radar Chart Round in R Using Plotly
    The Radar chart is used to represent multivariate independent data graphically. It's a circular chart where each independent variable has its own axis and all those axes are merged at the center of the radar chart. It is also known as Web Chart because it looks like Spider Web. This chart is used wh
    3 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