Create pie chart with random colors in Python

In this tutorial, we are going to see how to create a pie chart along with assigning the pie chart with random colors in Python. To do this, we must know about two libraries in python they are “matplotlib” and “random”. Let us see about matplotlib, it is a plotting library in python which is used to create graphs and charts for the given data this is widely in various sectors for various operations. Most of the segments of matplotlib are written in python and some segments are written in C and JavaScript.

Now, let us see about random library is used to display a random number or random character from a list or string which generates a random number with which random elements can be accessed and it can also be used to shuffle elements randomly similarly there are different kinds of operations are possible with random library.

Generation of the pie chart:

import matplotlib.pyplot as plt
n = int(input("Enter the values:"))
values = []
for i in range(n):
    x = int(input("Enter the number to be updated in the list: "))
    values.append(x)
plt.pie(values);
plt.show();

Output:

Enter the values:4
Enter the number to be updated in the list: 23
Enter the number to be updated in the list: 34
Enter the number to be updated in the list: 45
Enter the number to be updated in the list: 65

Create pie chart with random colors in Python

Explanation:

  • Firstly, the matplotlib library is imported with pyplot which consists of functions for creating simple 2D graphs and charts.
  • The number of elements to be inserted is obtained from the user.
  • An empty list I created and the values are appended inside the list.
  • pie() function is used to create the pie chart and then the pie chart is displayed using the show() function.

Generating random colors for pie chart:

import matplotlib.pyplot as plt, random
n = int(input("Enter the values:"))
values = []
color = []
for i in range(n):
    x = int(input("Enter the number to be updated in the list: "))
    values.append(x)
    r = random.random()
    g = random.random()
    b = random.random()
    color.append([r, g, b])
plt.pie(values,colors=color);
plt.show();

Output:

Enter the values:4
Enter the number to be updated in the list: 19
Enter the number to be updated in the list: 32
Enter the number to be updated in the list: 67
Enter the number to be updated in the list: 12

Create pie chart with random colors in Python

Same as the previous example elements are obtained from the user and are appended to the list. The random() function is used to generate random values which are used to generate the color. To display the color the pie() function is called along with the colors attribute which is used to display the random colors.

 

Leave a Reply

Your email address will not be published.