You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按特定变量计算列占比?基于DF按海盆绘制藻类覆盖珊瑚礁占比

嘿,我来帮你搞定这个需求!要基于DataFrame按海盆统计被藻类覆盖的珊瑚礁占比,再画出可视化图表,咱们分两步走:先处理数据算出占比,再做可视化展示。下面是具体的代码和细节说明:

步骤1:计算各海盆的藻类覆盖占比

首先得明确你的数据结构,常见的有两种情况,我都给你列出来:

情况1:数据已按海盆汇总

如果你的DF已经有按海盆分组后的总调查数和藻类覆盖数(比如列名是total_reefs和algae_reefs),那直接计算占比就行:

import pandas as pd

# 假设你的DF长这样
df = pd.DataFrame({
    'ocean_basin': ['Pacific', 'Atlantic', 'Indian'],
    'total_reefs': [500, 300, 400],
    'algae_reefs': [120, 80, 95]
})

# 计算占比,保留两位小数
df['algae_coverage_pct'] = (df['algae_reefs'] / df['total_reefs'] * 100).round(2)

情况2:原始数据是单条珊瑚礁记录

如果你的DF是每条记录对应一个珊瑚礁,有标记列(比如is_algae_covered,值为True/False或者1/0),那得先分组汇总再计算:

import pandas as pd

# 假设原始DF长这样
df = pd.DataFrame({
    'ocean_basin': ['Pacific', 'Pacific', 'Atlantic', 'Indian', 'Indian', 'Indian'],
    'is_algae_covered': [True, False, True, True, False, True]
})

# 分组计算:总数量和藻类覆盖数量
grouped_df = df.groupby('ocean_basin').agg(
    total_reefs=('is_algae_covered', 'count'),
    algae_reefs=('is_algae_covered', 'sum')  # True会被当作1求和
).reset_index()

# 计算占比
grouped_df['algae_coverage_pct'] = (grouped_df['algae_reefs'] / grouped_df['total_reefs'] * 100).round(2)
步骤2:绘制可视化图表

用matplotlib或者seaborn都可以,这里用seaborn做柱状图,对比不同海盆的占比会更直观:

import seaborn as sns
import matplotlib.pyplot as plt

# 设置图表风格
sns.set_style("whitegrid")

# 绘制柱状图
plt.figure(figsize=(10, 6))
bar_plot = sns.barplot(x='ocean_basin', y='algae_coverage_pct', data=grouped_df, palette='Blues_d')

# 添加数值标签到柱子上,方便看具体数值
for p in bar_plot.patches:
    bar_plot.annotate(f'{p.get_height()}%', 
                      (p.get_x() + p.get_width() / 2., p.get_height()),
                      ha='center', va='center',
                      xytext=(0, 9),
                      textcoords='offset points')

# 设置标题和坐标轴标签
plt.title('Percentage of Algae-Covered Coral Reefs by Ocean Basin', fontsize=14)
plt.xlabel('Ocean Basin', fontsize=12)
plt.ylabel('Coverage Percentage (%)', fontsize=12)
plt.ylim(0, 100)  # 占比范围固定在0-100%,更合理

# 显示图表
plt.show()

要是你想换图表类型(比如饼图),只需要把seaborn.barplot换成对应的绘图函数就行,不过柱状图在对比多组数据的时候可读性会更强。

内容的提问来源于stack exchange,提问作者Scott Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:32:43