Home > Blockchain >  How to have a section of a pie chart transparent
How to have a section of a pie chart transparent

Time:10-20

I want to highlight only the chemical section, so I want to keep the other section transparent. How can I achieve this?

import matplotlib.pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Chemicals', 'Oil & gas', 'Textiles& Mining' , 'Food & Breverages', 'Others'
colors = ['#01579B','#2E86C1','#3498DB','#2874A6','#1B4F72']
sizes = [31, 24, 7, 5,33 ]
explode = (0, 0, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, ax1 = plt.subplots()
patches, texts, autotexts =ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', startangle=90,colors=colors,textprops={'fontsize': 13})
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
[autotext.set_color('white') for autotext in autotexts]
[autotext.set_weight('bold') for autotext in autotexts]

plt.savefig('filename1.png', dpi=300)
plt.show()

CodePudding user response:

You can manually change the alpha of each patch in the pie-diagram. The following line sets all wedges to have alpha equal to zero except the first wedge as you wanted:

[patches[i].set_alpha(0) for i in range(len(patches)) if i not in [0]]

enter image description here

CodePudding user response:

You could use set_alpha e.g.:

import matplotlib.pyplot as plt


# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = [
    'Chemicals', 'Oil & gas', 'Textiles& Mining', 'Food & Breverages', 'Others'
]
colors = ['#01579B', '#2E86C1', '#3498DB', '#2874A6', '#1B4F72']
sizes = [31, 24, 7, 5, 33]
explode = (0, 0, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, ax1 = plt.subplots()
patches, texts, autotexts = ax1.pie(
    sizes, explode=explode, labels=labels, autopct='%1.1f%%', startangle=90,
    colors=colors, textprops={'fontsize': 13}
)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

selection = 'Chemicals'
for patch, text, autotext in zip(patches, texts, autotexts):
    autotext.set_color('white')
    autotext.set_weight('bold')
    if text.get_text() != selection:
        patch.set_alpha(0.5)

# plt.savefig('filename1.png', dpi=300)
plt.show()

But since you are already manually defining your colors, you could just as easily define paler colors for all the wedges that should not be highlighted.

  • Related