首页 > 解决方案 > 从列表中查找最大值并将其分配给饼图 MatPlotLib Python 中的爆炸值

问题描述

分解饼图

我在 matplotlib.pyplot 工作并且还在学习。我想分解饼图中的最大值。除了硬编码中的值,有没有办法从列表explode_values中找到最大值并分配相关性,同时将其余部分分配为零,这将消除对 的硬编码?y_axisexplode_valueexplode_values

import matplotlib.pyplot as plt

x_axis = ["Jan", "Feb", "Mar", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
# Set the y-axis to a list of floats as the total fare in US dollars accumulated for each month.
y_axis = [10.02, 23.24, 39.20, 35.42, 32.34, 27.04, 43.82, 10.56, 11.85, 27.90, 20.71, 20.09]

fig, ax =plt.subplots(figsize=(8,8))
colors = ["slateblue", "magenta", "lightblue", "green", "yellowgreen", "greenyellow", "yellow", "orange", "gold", "indianred", "tomato", "mistyrose"]
explode_values = (0, 0, 0.2, 0, 0, 0, 0.2, 0, 0, 0, 0, 0)
ax.pie(y_axis, labels=x_axis,
    autopct='%.1f%%',
    shadow=True,
    startangle=270.0,
    colors=colors,
    explode=explode_values)
ax.invert_yaxis()
plt.show()

标签: pythonmatplotlibcharts

解决方案


我想这就是你想要的

y_axis = [10.02, 23.24, 39.20, 35.42, 32.34, 27.04, 43.82, 10.56, 11.85, 27.90, 20.71, 20.09]
max_val = max(y_axis)
max_index = y_axis.index(max_val)
explode_value = tuple([0 if i!=max_index else 0.2 for i in range(len(y_axis))])
print(explode_value)

输出:(0, 0, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 0)

但是,如果您想根据 y_axis值设置爆炸值并将爆炸值保持在 0 到 1 的范围内,请尝试以下代码

x_axis = ["Jan", "Feb", "Mar", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
y_axis = [10.02, 23.24, 39.20, 35.42, 32.34, 27.04, 43.82, 10.56, 11.85, 27.90, 20.71, 20.09]
max_val = max(y_axis)
max_index = y_axis.index(max_val)
explode_value = tuple([0 if i!=max_index else round((max_val/sum(y_axis)),2) for i in range(len(y_axis))])
print(explode_value)

同样,如果您想根据 y_axis值和百分比设置爆炸值,请尝试以下代码

x_axis = ["Jan", "Feb", "Mar", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
y_axis = [10.02, 23.24, 39.20, 35.42, 32.34, 27.04, 43.82, 10.56, 11.85, 27.90, 20.71, 20.09]
max_val = max(y_axis)
max_index = y_axis.index(max_val)
explode_value = tuple([0 if i!=max_index else round((max_val/sum(y_axis)),2)*100 for i in range(len(y_axis))])
print(explode_value)

推荐阅读