垂直的柱形图,标注带线的标签,正向柱标签线起于坐标轴终于底部,负向柱标签起于坐标轴终于顶部:
- 柱状图的数据柱标上带线的标签,正向柱标签在底,负向柱标签在顶
- 用LabelOffset的对象fixedEnd控制数据标签的位置
- fixedEnd.posMode='low',正向柱的标签在底部
- fixedEnd.pos = -10,positive,负向移动10
- fixedEnd.negMode='high',负向柱的标签在顶部
- fixedEnd.neg = -10,negtive,正向向移动10
- 正向柱标签的锚点在n: **chart.barLabels.boxAnchor='n'**
- dy位移,微调整y轴上的位置: **chart.barLabels.dy = -1**
- 负向柱标签的锚点和dy'do the 'right thing'
- 正向柱和负向柱的标签线都始于坐标轴
- self.chart.barLabels.fixedStart = LabelOffset()
- self.chart.barLabels.fixedStart.posMode='axis'
- self.chart.barLabels.fixedStart.negMode='axis'
代码与注释:
"A Vertical Bar Chart With Line Indicated Bar Labels"
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin
from reportlab.lib.colors import blue
from reportlab.graphics.charts.textlabels import LabelOffset
class BarChart_VRevLineLabels(_DrawingEditorMixin,Drawing):
def __init__(self,width=400,height=200,*args,**kw):
Drawing.__init__(self,width,height,*args,**kw)
self._add(self,VerticalBarChart(),name='chart',validate=None,desc=None)
self.chart.y = 20
self.chart.width=self.width-self.chart.x - 5
self.chart.height=self.height-2*self.chart.y
self.chart.data = [(100, -110),(25,-30)]
self.chart.barLabelFormat = '%s' # 标签格式
self.chart.barLabels.lineStrokeColor = blue # 标签线颜色
self.chart.barLabels.lineStrokeWidth = 1 # 标签线宽度
self.chart.barLabels.fixedStart = LabelOffset() # 生产LabelOffset对象
self.chart.barLabels.fixedStart.posMode='axis' # 正向标签线起点坐标轴
self.chart.barLabels.fixedStart.negMode='axis' # 负向标签线起点坐标轴
self.chart.barLabels.fixedEnd = LabelOffset() # 生产LabelOffset对象
self.chart.barLabels.fixedEnd.posMode='low' # 正向标签居于底
self.chart.barLabels.fixedEnd.pos = -10 # 正向标签向下10
self.chart.barLabels.fixedEnd.negMode='high' # 负向标签居于顶
self.chart.barLabels.fixedEnd.neg = 10 # 负向标签向上10
self.chart.barLabels.boxAnchor='n' # 锚点n
self.chart.barLabels.dy = 1 # y轴方向向上微调1
if __name__=="__main__":
BarChart_VRevLineLabels().save(formats=['pdf'],outDir='.',fnRoot=None)