Develop a code for bar chart pie chart in matplotlib.

10 c] Develop a code for bar chart pie chart in matplotlib.

Bar Chart

The plt.bar(x, height, [width]) creates a vertical bar plot. For horizontal bars, use the plt.barh() function.
Important parameters:

  • x: Specifies the x coordinates of the bars
  • height: Specifies the height of the bars
  • width (optional): Specifies the width of all bars; the default is 0.8

Example

labels = ['A', 'B', 'C', 'D']
x = np.arange(len(labels))
width = 0.4
plt.bar(x – width / 2, [20, 25, 40, 10], width=width)
plt.bar(x – width / 2, [30, 15, 30, 20], width=width)
# Ticks and tick labels must be set manually
plt.ticks(x)
ax = plt.gca()
ax.set_xticklabels(labels)
bar chart
Pie Chart

The plt.pie(x, [explode], [labels], [autopct]) function creates a pie chart.
Important parameters:

  • x: Specifies the slice sizes.
  • explode (optional): Specifies the fraction of the radius offset for each slice. The
    explode-array must have the same length as the x-array.
  • labels (optional): Specifies the labels for each slice.
  • autopct (optional): Shows percentages inside the slices according to the specified
    format string. Example: ‘%1.1f%%’.

Example:

plt.pie([0.4, 0.3, 0.2, 0.1], explode=(0.1, 0, 0, 0), labels=['A', 'B', 
'C', 'D'])
pie chart

Leave a Reply

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