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

使用R中FacetGrid绘制多面板条形图的需求与问题排查

解决方案(Python + Seaborn实现)

直接用Seaborn的FacetGrid搭配条形图实现需求,以下是完整代码和注意事项:

步骤1:导入依赖库

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

步骤2:加载并清洗数据

先把原始数据整理成可处理的DataFrame,处理掉字段间的空格:

# 直接硬编码原始数据(也可替换为读取本地文件)
data = pd.DataFrame([
    ["A", "Last_year", "north", "mornings", 10],
    ["A", "Last_year", "south", "mornings", 20],
    ["A", "Last_year", "north", "evenings", 45],
    ["A", "Last_year", "south", "evenings", 35],
    ["A", "this_year", "north", "mornings", 80],
    ["A", "this_year", "south", "mornings", 60],
    ["A", "this_year", "north", "evenings", 95],
    ["A", "this_year", "south", "evenings", 120],
    ["A", "study_year", "north", "mornings", 100],
    ["A", "study_year", "south", "mornings", 400],
    ["A", "study_year", "north", "evenings", 220],
    ["A", "study_year", "south", "evenings", 32],
    ["B", "Last_year", "north", "mornings", 10],
    ["B", "Last_year", "south", "mornings", 45],
    ["B", "Last_year", "north", "evenings", 25],
    ["B", "Last_year", "south", "evenings", 20],
    ["B", "this_year", "north", "mornings", 300],
    ["B", "this_year", "south", "mornings", 250],
    ["B", "this_year", "north", "evenings", 140],
    ["B", "this_year", "south", "evenings", 20],
    ["B", "study_year", "north", "mornings", 10],
    ["B", "study_year", "south", "mornings", 20],
    ["B", "study_year", "north", "evenings", 10],
    ["B", "study_year", "south", "evenings", 20],
], columns=["Name", "Active_period", "site", "Time", "count"])

步骤3:绘制多面板水平条形图

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

# 创建多面板布局:垂直按site分面板,水平按Time分面板
g = sns.FacetGrid(
    data,
    row="site",
    col="Time",
    margin_titles=True,
    height=4,
    aspect=1.2
)

# 绘制水平条形图,用Active_period区分颜色
g.map_dataframe(
    sns.barplot,
    x="count",
    y="Name",
    hue="Active_period",
    orientation="h",
    palette="tab10"
)

# 给每个条形添加count数值标签
for ax in g.axes.flat:
    for p in ax.patches:
        width = p.get_width()
        y_pos = p.get_y() + p.get_height() / 2
        ax.text(
            width + 2,  # 标签偏移,避免和条形重叠
            y_pos,
            f"{int(width)}",
            va="center",
            fontsize=9
        )

# 调整图表细节
g.add_legend(title="Active Period")
g.set_axis_labels("Count", "Name")
g.set_titles(row_template="Site: {row_name}", col_template="Time: {col_name}")
plt.tight_layout()
plt.show()

避坑关键点

  • 确保count字段是数值类型,否则会出现类型错误
  • 水平条形图必须指定orientation="h",同时对应x=count、y=Name的参数顺序
  • 统一用g.add_legend()添加图例,避免每个子图重复显示图例
  • 添加数值标签时,通过ax.patches遍历所有条形,避免索引越界报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:05:28