donut chart python

  • Last Update :
  • Techknowledgy :

Last Updated : 02 Feb, 2022

To add legends we will simply write the following code.

plt.legend(labels, loc = "upper right")

We can add a title to the Legend Box in Donut Chart by writing the following code:

plt.legend(labels, loc = "upper right", title = "Fruits Color")

Suggestion : 2

A Donut chart is essentially a Pie Chart with an area of the center cut out. You can build one hacking the plt.pie() function of the matplotlib library as shown in the examples below.,matplotlib allows to build a pie chart easily thanks to its pie() function. Visit the dedicated section for more about that.,As his friend the Pie chart, the Donut chart is often criticized. Humans are pretty bad at reading angles, making it hard to rank the groups accurately. Most of the time, it is better to display the information as a barchart, a treemap or a lollipop plot.,We can use the exact same principle and add a circle to the center thanks to thecircle() function and get a donut chart.🔥

# library
import matplotlib.pyplot as plt

# create data
size_of_groups = [12, 11, 3, 30]

# Create a pieplot
plt.pie(size_of_groups)

# add a circle at the center to transform it in a donut chart
my_circle = plt.Circle((0, 0), 0.7, color = 'white')
p = plt.gcf()
p.gca().add_artist(my_circle)

plt.show()

Suggestion : 3

Donut Charts or Doughnut Charts are a special kind of Pie chart with the difference that it has a Blank Circle at the center. The whole ring represents the data series taken into consideration. Each piece of this ring represents the proportion of the whole Data Series or percentage of total if the whole ring represents 100% of data. Donut Chart got its name from the Donuts which has a circle at its center.,**The Donut Charts shown above are not the actual representation of what we get as an output. Since we used np.random(), we will get a different Donut Chart every time we run the given code.,The whole pie chart can be built with one infamous matplotlib library of Python. It is built the same way pie charts are built with some additional commands to get the blank space at the center.,Donut Chart with Percent of Total Values as Annotations and First Part Exploded

1. Importing Libraries

import numpy as np
import matplotlib.pyplot as plt

3. Plotting Pie Chart of the made-up data

plt.pie(data)

4. Creating a Circle

circle = plt.Circle((0, 0), 0.7, color = 'white')

6. Putting it all together

import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(20, 100, 6)
plt.pie(data)
circle = plt.Circle((0, 0), 0.7, color = 'white')
p = plt.gcf()
p.gca().add_artist(circle)
plt.show()

1. Adding Annotations to the Donut Chart

import matplotlib.pyplot as plt
import numpy as np
data = np.random.randint(20, 100, 6)
plt.pie(data, labels = ['A', 'B', 'C', 'D', 'E', 'F'])
circle = plt.Circle((0, 0), 0.7, color = 'white')
p = plt.gcf()
p.gca().add_artist(circle)
plt.show()

Suggestion : 4

Welcome to the Matplotlib bakery. We will create a pie and a donut chart through the pie method and show how to label them with a legend as well as with annotations.,We then want to label the wedges via annotations. We first create some dictionaries of common properties, which we can later pass as keyword argument. We then iterate over all wedges and for each,As usual we would start by defining the imports and create a figure with subplots. Now it's time for the pie. Starting with a pie recipe, we create the data and a list of labels from it.,We can provide a function to the autopct argument, which will expand automatic percentage labeling by showing absolute values; we calculate the latter back from relative data and the known sum of all values.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize = (6, 3), subplot_kw = dict(aspect = "equal"))

recipe = ["375 g flour",
   "75 g sugar",
   "250 g butter",
   "300 g berries"
]

data = [float(x.split()[0]) for x in recipe]
ingredients = [x.split()[-1]
   for x in recipe
]

def func(pct, allvals):
   absolute = int(np.round(pct / 100. * np.sum(allvals)))
return "{:.1f}%\n({:d} g)".format(pct, absolute)

wedges, texts, autotexts = ax.pie(data, autopct = lambda pct: func(pct, data),
   textprops = dict(color = "w"))

ax.legend(wedges, ingredients,
   title = "Ingredients",
   loc = "center left",
   bbox_to_anchor = (1, 0, 0.5, 1))

plt.setp(autotexts, size = 8, weight = "bold")

ax.set_title("Matplotlib bakery: A pie")

plt.show()
fig, ax = plt.subplots(figsize = (6, 3), subplot_kw = dict(aspect = "equal"))

recipe = ["225 g flour",
   "90 g sugar",
   "1 egg",
   "60 g butter",
   "100 ml milk",
   "1/2 package of yeast"
]

data = [225, 90, 50, 60, 100, 5]

wedges, texts = ax.pie(data, wedgeprops = dict(width = 0.5), startangle = -40)

bbox_props = dict(boxstyle = "square,pad=0.3", fc = "w", ec = "k", lw = 0.72)
kw = dict(arrowprops = dict(arrowstyle = "-"),
   bbox = bbox_props, zorder = 0, va = "center")

for i, p in enumerate(wedges):
   ang = (p.theta2 - p.theta1) / 2. + p.theta1
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
horizontalalignment = {
   -1: "right",
   1: "left"
} [int(np.sign(x))]
connectionstyle = "angle,angleA=0,angleB={}".format(ang)
kw["arrowprops"].update({
   "connectionstyle": connectionstyle
})
ax.annotate(recipe[i], xy = (x, y), xytext = (1.35 * np.sign(x), 1.4 * y),
   horizontalalignment = horizontalalignment, ** kw)

ax.set_title("Matplotlib bakery: A donut")

plt.show()

Suggestion : 5

In go.Pie, data visualized by the sectors of the pie is set in values. The sector labels are set in labels. The sector colors are set in marker.colors.,In the example below, we first create a pie chart with px,pie, using some of its options such as hover_data (which columns should appear in the hover) or labels (renaming column names). For further tuning, we call fig.update_traces to set other parameters of the chart (you can also use fig.update_layout for changing the layout).,For a figure fig created with plotly express, use fig.update_traces(insidetextorientation='...') to change the text orientation.,Plotly Express is the easy-to-use, high-level interface to Plotly, which operates on a variety of types of data and produces easy-to-style figures.

import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Europe'")
df.loc[df['pop'] < 2.e6, 'country'] = 'Other countries'
# Represent only large countries
fig = px.pie(df, values = 'pop', names = 'country', title = 'Population of European continent')
fig.show()
import plotly.express as px
# This dataframe has 244 lines, but 4 distinct values
for `day`
df = px.data.tips()
fig = px.pie(df, values = 'tip', names = 'day')
fig.show()
import plotly.express as px
df = px.data.tips()
fig = px.pie(df, values = 'tip', names = 'day', color_discrete_sequence = px.colors.sequential.RdBu)
fig.show()
import plotly.express as px
df = px.data.tips()
fig = px.pie(df, values = 'tip', names = 'day', color = 'day',
   color_discrete_map = {
      'Thur': 'lightcyan',
      'Fri': 'cyan',
      'Sat': 'royalblue',
      'Sun': 'darkblue'
   })
fig.show()
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = px.pie(df, values = 'pop', names = 'country',
   title = 'Population of American continent',
   hover_data = ['lifeExp'], labels = {
      'lifeExp': 'life expectancy'
   })
fig.update_traces(textposition = 'inside', textinfo = 'percent+label')
fig.show()
import plotly.graph_objects as go

labels = ['Oxygen', 'Hydrogen', 'Carbon_Dioxide', 'Nitrogen']
values = [4500, 2500, 1053, 500]

fig = go.Figure(data = [go.Pie(labels = labels, values = values)])
fig.show()

Suggestion : 6
import pandas as pd
df = pd.read_json("datanew.json")
print(df.head())
df.drop(df.tail(1).index, inplace = True)
df1 = df.sort_values(by = 'active', ascending = False)
df3 = df1[: 5]