Create a Pie chart using Plotly in Python

In this tutorial, we will learn about what is a pie chart and how to install a Plotly library. We will also learn what are the functions to create pie charts using Plotly and how to create a pie chart using those functions.

How to install Plotly?

We can install Plotly using the pip command in Python as follows

pip install plotly

This will install the latest version of the Plotly library in your system.

What are the methods to create a pie chart in Plotly?

We can create a pie chart using the following methods:

  1. Using go.pie() method
  2. Using px.pie() method(plotly express)

1)Using the go.pie() method

import plotly.graph_objects as go
labels1 = ['A', 'B', 'C']
values1 = [10, 20, 30]
data1=go.Pie(labels=labels1, values=values1)
fig = go.Figure(data=data1)
fig.show()

In the above code, first, we import the .go() class from plotly.graph objects. Then we create labels and values and store those in a list. Using the go.pie() method we create dataset ‘data1’. The parameter values we are passing as labels1 and values1. Then finally we create a figure object using go.Figure() method and display it.

Output:

Create a Pie chart using Plotly in Python

2) Using px.pie() method

import plotly.express as px
labels = ['A', 'B', 'C']
values = [80, 60, 30]
data = {'Categories': labels, 'Values': values}
fig = px.pie(data, names='Categories', values='Values', title='Pie Chart using px.pie() function')
fig.show()

In the above code, we are importing plotly express as px. Then we create labels and a values list. Using labels and values we are storing that data in dictionary form (you can create a data frame also and use it for visualization). Finally, we are creating px.pie() object. It takes parameter values as data, labels, and values we defined in the above code.

Output:

px.pie() method

Leave a Reply

Your email address will not be published. Required fields are marked *