要在 ReportLab 中的饼图中显示数量和比例的标签,可以使用 PieChart 类中的 label_options 参数。label_options 参数是一个字典,其中可以设置以下选项:

  • 'label_position': 标签位置,可以是 'inside' 或 'outside'。
  • 'label_font': 标签字体,可以是一个字符串,例如 'Helvetica-Bold'。
  • 'label_font_size': 标签字体大小,可以是一个整数。
  • 'label_color': 标签颜色,可以是一个元组,例如 (0, 0, 0) 表示黑色。
  • 'label_format': 标签格式,可以是一个字符串,例如 '%.2f%%' 表示保留两位小数的百分比。

下面是一个示例代码:

from reportlab.graphics.charts.piecharts import Pie
from reportlab.graphics.shapes import Drawing
from reportlab.lib.colors import Color

data = [(10, 'A'), (20, 'B'), (30, 'C'), (40, 'D')]
drawing = Drawing(width=400, height=400)
chart = Pie()
chart.data = [row[0] for row in data]
chart.labels = [row[1] for row in data]
chart.slices.strokeWidth = 0.5
chart.slices[0].popout = 10
chart.slices[0].labelRadius = 1.2
chart.slices[0].fontColor = Color(255, 255, 255)
chart.slices[0].fontSize = 14
chart.slices[0].fontName = 'Helvetica-Bold'
chart.slices[0].labelFormat = '%d (%.1f%%)'
chart.label_options = {'label_position': 'inside', 'label_font_size': 10}
drawing.add(chart)
drawing.save()

这个例子中,我们创建了一个包含 4 个数据点的饼图,每个数据点包含一个数字和一个标签。我们设置了第一个数据点的标签显示在饼图中间,其他数据点的标签显示在饼图外部。我们还设置了第一个数据点的标签字体为 Helvetica-Bold,字体大小为 14,标签格式为 '%d (%.1f%%)' 即显示数字和百分比。其他数据点的标签字体大小为 10。最终生成的图表如下图所示:

reportlab_pie_chart_with_labels.png

ReportLab 饼图:显示数量和比例标签

原文地址: https://www.cveoy.top/t/topic/oNsL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录