Data Science Explorer

Matplotlib Pie Charts 본문

Python

Matplotlib Pie Charts

grace21110 2023. 11. 11. 21:12
반응형
  • Creating Pie Charts 

You can use the pie() function to draw pie charts 

 

Example 

import matplotlib.pyplot as plt 
import numpy as np 

y = np.array ([3, 6, 7, 1]) 

plt.pie(y)
plt.show()

Result 

 

  • Labels 

The label parameter must be an array with one label for each wedge. 

import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels)
plt.show()

Result 

 

  • Explode 

If you want to make the parameter standing out, you can use explode parameter. 

import matplotlib.pyplot as plt 
import numpy as np 

y = np.array ([4, 8, 1, 2])

mylabels =["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0.3, 0]

plt.pie (y, labels = mylabels, explode = myexplode)
plt.show()

Result 

 

 

 

  • Shadow 

You can add a shadow to the pie chart by using shadow parameter.

 

Example 

import matplotlib.pyplot as plt 
import numpy as np 

y = np.array ([4, 8, 1, 2])

mylabels =["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0.3, 0]

plt.pie (y, labels = mylabels, explode = myexplode, shadow = True)
plt.show()

Result 

 

  • Colors 

You can change the color of the pie chart with color parameter. 

 

Example 

import matplotlib.pyplot as plt 
import numpy as np 

y = np.array ([4, 8, 1, 2])

mylabels =["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0.3, 0]
mycolors = ['black', 'red', 'b', 'white']

plt.pie (y, labels = mylabels, explode = myexplode, shadow = True, colors = mycolors)
plt.show()

Result 

 

  • Legend 

To add a list of explanation for each wedge, you can use legend() function. 

 

Example 

import matplotlib.pyplot as plt
import numpy as np

y = np.array([2,5,9,8])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels)
plt.legend()
plt.show()

Result 

 

 

  • Legend with Header 

If you want to add a header, you can add title to legend function.

 

Example 

import matplotlib.pyplot as plt 
import numpy as np 

y = np.array ([1, 2, 3, 4]) 
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie (y, labels = mylabels)
plt.legend(title = "Fruits")
plt.show()

Result 

'Python' 카테고리의 다른 글

[Basic Grammar] Python Inheritance  (0) 2023.11.21
[Basic Grammar] Python Classes/Objects  (1) 2023.11.19
Matplotlib Histograms  (0) 2023.11.10
Matplotlib Bars  (2) 2023.11.09
Matplotlib Scatter  (0) 2023.11.08