python - 从列表中查找最大值并将其分配给饼图 MatPlotLib Python 中的爆炸值
问题描述
我在 matplotlib.pyplot 工作并且还在学习。我想分解饼图中的最大值。除了硬编码中的值,有没有办法从列表explode_values
中找到最大值并分配相关性,同时将其余部分分配为零,这将消除对 的硬编码?y_axis
explode_value
explode_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()
解决方案
我想这就是你想要的
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)
推荐阅读
- c# - 更新数据网格视图中的 Excel 文件并保存到数据库
- javascript - 获得一个 promiseValue
- html - XSLT:组织用于打印的 html 表格
- asp.net-core - .Net Core 2.1 System.IO.FileSystem.DriveInfo
- css - 关于溢出浮动div,margin-right 和left 以不同的方式工作
- java - 缺少 JNI 库
- c++ - gRPC 和 etcd 客户端
- windows - Cortana 不允许我在搜索框中输入超过 2 个字母并挂在 Windows 10 中
- c++ - 工厂方法模式使用继承,而抽象工厂模式使用组合如何?
- iframe - 如何在机器人框架骑行编辑器中从 iframe 标记中定位元素