python reportlab categoryAxis标签放置

时间:2018-03-23 15:20:17

标签: python reportlab

我编写了一个简单的函数,可以从单个数据系列生成一个简单的条形图,如下所示。输入数据可以是正数或负数,当负数表示条形图标签被条形图覆盖时(下面的代码中的图表2和3)。

我搜索了reportlab graphics reference,并在第202页显示了标签位置为“低”的条形图。但是,用于执行此操作的命令:bc.categoryAxis.labels.dy = -60,似乎是任意选择的。如果输入数据未知,如何知道负偏移?有没有办法识别图纸上的x轴位置,然后确定该位置的标签偏移量,或输入数据未知时的任何其他解决方法?

感谢任何指导。

from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics.charts.textlabels import Label
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter

def vbar_one_series(data, xlabels, chart_title, xaxis_text):
    drawing = Drawing(180, 180)

    bc = VerticalBarChart()
    bc.x = 25
    bc.y = 25
    bc.height = 125
    bc.width = 150
    bc.data = [data]
    bc.valueAxis.valueMin = int(min(min(bc.data[0]), 0))
    bc.valueAxis.valueMax = int(max(bc.data[0]) + 2)
    bc.valueAxis.labels.fontName = 'Helvetica'
    bc.valueAxis.labels.fontSize = 7
    bc.valueAxis.labelTextFormat = '%0.1f'
    bc.bars[0].fillColor = colors.HexColor('#000035')
    bc.categoryAxis.labels.boxAnchor = 'c'
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.labels.fontSize = 7
    bc.categoryAxis.tickDown = 0
    bc.categoryAxis.labels.dx = 0
    bc.categoryAxis.labels.dy = -7
    bc.categoryAxis.labels.angle = 0

    bc.categoryAxis.categoryNames = xlabels

    bc.barLabels.nudge = 10
    bc.barLabelFormat = '%0.1f'
    bc.barLabels.dx = 0
    bc.barLabels.dy = 0
    bc.barLabels.fontName = 'Helvetica'
    bc.barLabels.fontSize = 7

    xlabel = Label()
    xlabel.setText(xaxis_text)
    xlabel.fontSize = 7
    xlabel.fontName = 'Helvetica'
    xlabel.dx = 90
    xlabel.dy = 5

    title = Label()
    title.setText(chart_title)
    title.fontSize = 7
    title.fontName = 'Helvetica'
    title.dx = 90
    title.dy = 175

    drawing.add(bc)
    drawing.add(xlabel)
    drawing.add(title)

    return drawing

if __name__ == '__main__':

    bar1 = vbar_one_series([1.0, 2.3, 1.8], ['A', 'B', 'C'],
                                 'Title 1', '')

    bar2 = vbar_one_series([-25, 50, 10], ['A', 'B', 'C'],
                           'Title 2', '')

    bar3 = vbar_one_series([0, -1.1, -0.4], ['A', 'B', 'C'],
                           'Title 3', '')

    doc = SimpleDocTemplate('H:/Desktop/report.pdf', pagesize=letter,
                            topMargin=0.5 * inch, bottomMargin=0.5 * inch)
    Catalog = []
    Catalog.append(bar1)
    Catalog.append(bar2)
    Catalog.append(bar3)
    doc.build(Catalog)

report.pdf

1 个答案:

答案 0 :(得分:0)

经过一些额外的研究后,我发现这个问题可以通过.categoryAxis.labelAxisMode =' low'来解决。属性。