如何高效为Pandas DataFrame各标签生成并保存单独折线图?
解决方案
方案1:用Seaborn FacetGrid批量生成子图
Seaborn的FacetGrid是专为按类别批量绘图设计的工具,无需手动拆分DataFrame,代码更简洁且样式易统一:
import seaborn as sns import matplotlib.pyplot as plt # 设置全局绘图样式 sns.set_style("dark") # 创建分面网格,按labels列分组,col_wrap控制每行子图数量 g = sns.FacetGrid(df_labels, col="labels", col_wrap=4, height=3, aspect=1.2, facecolor='#293952') # 为每个子图绘制折线图 g.map(sns.lineplot, "event_date", "counts", color='#FDAC53', linewidth=2.5) # 调整子图间距,避免标题、标签重叠 g.tight_layout() # 保存整组分面图 g.savefig("all_labels_facets.png", dpi=100) # 若需单独保存每个子图 for idx, ax in enumerate(g.axes.flat): label = df_labels['labels'].unique()[idx] # 单独保存时需指定画布,避免截断 fig = ax.get_figure() fig.savefig(f"chart_{label}.png", dpi=100)
方案2:用groupby高效分组绘图
如果偏好手动控制每个子图的细节,可直接用groupby获取分组数据,省去手动创建单独DataFrame的步骤:
import seaborn as sns import matplotlib.pyplot as plt # 按labels分组遍历 for label, group_data in df_labels.groupby('labels'): fig, ax = plt.subplots(1, facecolor='#293952') sns.lineplot(data=group_data, x='event_date', y='counts', color='#FDAC53', linewidth=2.5, ax=ax) ax.set_title(f"每日事件统计:{label}") ax.set_xlabel("日期") ax.set_ylabel("事件数量") plt.savefig(f"chart_{label}.png", dpi=100) plt.close() # 关闭画布,释放内存
额外优化:交互式图表(无需拆分图片)
如果不想生成大量静态图片,可使用Plotly创建交互式图表,支持通过图例开关单独查看任意label的折线:
import plotly.express as px fig = px.line(df_labels, x='event_date', y='counts', color='labels', title="各Label每日事件统计") fig.update_layout(xaxis_title="日期", yaxis_title="事件数量") fig.write_html("interactive_label_stats.html")
内容的提问来源于stack exchange,提问作者ozzboy
相关产品推荐
相关产品推荐

