matplotlib 如何使饼图的一部分透明

goqiplq2  于 2023-08-06  发布在  其他
关注(0)|答案(3)|浏览(130)

我只想突出显示化学部分,所以我想保持其他部分透明。我该如何实现这一点?

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()

字符串

dluptydi

dluptydi1#

您可以手动更改饼图中每个面片的alpha。下面的行根据需要将除第一个楔形之外的所有楔形设置为alpha等于零:

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

字符串


的数据

acruukt9

acruukt92#

您可以使用set_alpha,例如:

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()

字符串
但是,由于您已经手动定义了颜色,因此可以轻松地为所有不应突出显示的楔形定义较浅的颜色。

yruzcnhs

yruzcnhs3#

根据Yashmeet Singh的How to Customize Pie Charts using Matplotlib教程,您还可以使用 set_visible() 方法而不是 set_alpha()。也就是说,如果你想让楔形完全消失。从mapf'sanswer获取代码,您只需在最后的 for-循环中执行以下操作:

[...]

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_visible(False)
        text.set_visible(False)
        autotext.set_visible(False)

[...]

字符串
正如您所看到的,textautotext 具有相同的属性,因此您也可以使它们不可见。
Image of the resulting one wedge pie chart.

相关问题