Python matplotlib柱状图标签优化及图表插入邮件方法咨询
柱状图标签优化方案
1 代码修改说明
你需要调整bar_label的格式参数,同时增加标签位置、旋转相关的配置,另外你现有代码中重复调用了两次柱状图绘制(sqldata.plot和ax.bar),会导致图形重叠,修改版中已去掉冗余逻辑:
import matplotlib as mpl import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-darkgrid') fig, ax = plt.subplots(figsize=(12, 6)) # 加大画布尺寸避免标签拥挤 x = np.arange(len(sqldata)) width = 0.35 # 绘制柱状图 rects1 = ax.bar(x - width/2, sqldata.t0, width, label='T+0') rects2 = ax.bar(x + width/2, sqldata.t30, width, label='T+30') # 坐标轴和标题配置 ax.set_title(f"Financials Team Cash Sheet {todaydate}") ax.set_ylabel('Cash') ax.set_xlabel('Account') ax.set_xticks(x) ax.set_xticklabels(sqldata['AccountName'], rotation=45, ha='right') # 旋转x轴账户名避免重叠 ax.set_ylim(0,30000000) ax.legend() plt.ticklabel_format(style='plain', axis='y') ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('${x:,.0f}')) # ---------------------- 核心修改部分 ---------------------- # 1. 设置千分位+2位小数的会计格式,如需带美元符号可改为'${:,.2f}' label_format = '{:,.2f}' # 2. 调整标签位置、旋转角度、字体大小优化可读性 ax.bar_label(rects1, padding=8, # 加大和柱体的间距避免遮挡 fmt=label_format, label_type='edge', # 标签放在柱体顶端不遮挡柱体内容 rotation=30, # 小幅旋转避免相邻标签重叠 fontsize=9) ax.bar_label(rects2, padding=8, fmt=label_format, label_type='edge', rotation=30, fontsize=9) # ----------------------------------------------------------- plt.tight_layout() # 提前存图方便后续插入邮件 plt.savefig('cash_sheet.png', dpi=300, bbox_inches='tight') plt.show()
2 图表插入邮件正文的最简单方法
- 手动发邮件场景:直接使用代码生成的
cash_sheet.png本地文件,打开邮件编辑页面点击「插入图片」选择该文件即可,无需额外配置。 - Python自动发邮件场景:可以用smtplib结合email库将图片转为内嵌资源插入HTML正文,极简示例如下:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage # 基础邮件配置 msg = MIMEMultipart('related') msg['Subject'] = '财务现金报表' msg['From'] = '你的邮箱地址' msg['To'] = '收件人邮箱地址' # HTML正文,关联图片ID html = ''' <p>您好,最新现金报表如下:</p> <img src="cid:cash_sheet"> ''' msg.attach(MIMEText(html, 'html', 'utf-8')) # 加载本地图片并设置资源ID with open('cash_sheet.png', 'rb') as f: img = MIMEImage(f.read()) img.add_header('Content-ID', '<cash_sheet>') msg.attach(img) # 发送邮件(以QQ邮箱为例,其他邮箱替换对应SMTP地址和端口即可) with smtplib.SMTP_SSL('smtp.qq.com', 465) as server: server.login('你的邮箱地址', '你的邮箱授权码') server.send_message(msg)
内容的提问来源于stack exchange,提问作者Maestro
相关产品推荐
相关产品推荐

