python - Pygal 图表中的居中对齐标题

标签 python svg pygal

我正在 Pygal 中制作折线图。我想将图表的标题居中,但我不知道该怎么做。

我尝试查看 Pygal 文档,但找不到任何与标题对齐相关的内容。这是我拥有的:

enter image description here

custom_style = Style(
    background = 'transparent',
    font_family='Avenir',
    colors = ['#14A1FF', '#14FF47'],
    opacity = .5)

chart = pygal.Line(
    style=custom_style, 
    print_values=True, 
    interpolate='hermite', 
    fill=True, dots_size=4, 
    show_y_guides=False,
    legend_at_bottom=True,
    legend_at_bottom_columns=2)

chart.title = "Rubik's Cube Solve Times Recorded Over Five Days"
chart.x_labels = ["1", "2", "3", "4", "5"]
chart.x_title = "Day"
chart.y_title = "Seconds"
chart.add("Average of 100", ao100)
chart.add("Average of 25", ao25)
chart.render_to_file('times.svg')

最佳答案

如评论中所述,图形标题相对于图形而不是轴居中。这种行为是硬编码在渲染函数中的,没有任何配置选项可以改变它。

一种解决方法是创建您自己的类,该类继承自 pygal.Line 并覆盖呈现标题(不是很大)的函数:

class MyLineChart(pygal.Line):

    def __init__(self, *args, **kwargs):
        super(MyLineChart, self).__init__(*args, **kwargs)

    def _make_title(self):
        """Make the title"""
        if self._title:
            for i, title_line in enumerate(self._title, 1):
                self.svg.node(
                    self.nodes['title'],
                    'text',
                    class_='title plot_title',
                    x=self.margin_box.left + self.view.width / 2, # Modified
                    y=i * (self.style.title_font_size + self.spacing)
                ).text = title_line

上面的_make_title 函数是直接从the source code for the Graph class 复制的(Line 本身继承自的类)。唯一的变化是在注释“修改”指示的行中,这是从呈现 x 轴标签的函数中获取的(因为它以轴为中心)。

有了它,您可以将 chart = pygal.Line 替换为 chart = MyLineChart,但保留其余代码。您可能还想将类的名称更改为更有意义的名称。

关于python - Pygal 图表中的居中对齐标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55320324/

相关文章:

python - 当 spss.Submit() 内的 spss 命令会创建警告时,SPSS-Python 脚本会停止并出现错误

python - 代表文件系统表

python - Flask 渲染 svg 文件,没有交互性

python - 在 Flask 中生成动态 Pygal 图表

css - 将省略号添加到 SVG 中的溢出文本?

django - 我如何在 Django 模板中嵌入 pygal 图表

python - 为什么字典中的项目顺序在 Python 中发生了变化?

python - 使用 pygame 和 lambda 实现撤消和重做

android - 没有当前类的引用,svgLoader 无法工作

python - 如何使用 Python 获取 SVG 路径的高度、宽度和长度?