Skip to content
Programs · Program 4-16

Q.(Program 4-16) Given a DataFrame with information about the planets' mass and radius — df = pd.DataFrame({'mass': [0.330, 4.87, 5.97], 'radius': [2439.7, 6051.8, 6378.1]}, index=['Mercury', 'Venus', 'Earth']) — plot a pie chart of the 'mass' column.

CBSENCERTSubjective· 3mImportance★★★★★est
43% · 19/44 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

A pie chart shows parts of a whole; here we visualize each planet's mass as a slice of the total mass in the DataFrame.

Why a pie chart is the wrong tool (but we'll plot it anyway)

A pie chart divides a circle into slices whose areas are proportional to each value's share of the total. It answers the question "what fraction of the whole does each category represent?"

For planetary masses, this is misleading. The three planets shown (Mercury, Venus, Earth) are not the only planets, so their masses do not form a meaningful "whole." A bar chart would be more honest. Nevertheless, the question asks for a pie chart, so we will produce one — understanding that it implies these three masses are the complete set we care about.

Pandas integrates tightly with Matplotlib. Calling .plot.pie() on a Series (a single column) generates the chart directly, using the index as labels and the values as slice sizes.

The code

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {'mass': [0.330, 4.87, 5.97], 
     'radius': [2439.7, 6051.8, 6378.1]},
    index=['Mercury', 'Venus', 'Earth']
)

df['mass'].plot.pie(autopct='%1.1f%%', startangle=90)
plt.ylabel('')  # Remove the default 'mass' label on the y-axis
plt.title('Planetary Mass Distribution')
plt.show()

Key lines explained

df['mass'] extracts the mass column as a Series. The index (['Mercury', 'Venus', 'Earth']) becomes the slice labels.

.plot.pie(autopct='%1.1f%%', startangle=90) creates the pie chart. autopct='%1.1f%%' displays each slice's percentage (one decimal place) inside the slice. startangle=90 rotates the chart so the first slice starts at the top (12 o'clock) rather than the right (3 o'clock), which is conventional.

plt.ylabel('') removes the automatic y-axis label "mass" that Pandas adds. A pie chart has no y-axis, so the label is clutter.

plt.title(…) and plt.show() add a title and display the figure. …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.