使用 Pygal 在 Python 中设计数据绘图样式

一个更时尚的 Python 绘图库的介绍。
92 位读者喜欢这个。
How to write a web service using Python Flask

Yuko Honda 在 Flickr 上。CC BY-SA 2.0

Python 充满了可以可视化数据的库。Pygal 是更具交互性的选项之一,我将其视为适合喜欢美观事物的人的库。它生成漂亮的 SVG(可缩放矢量图形)文件,用户可以与之交互。SVG 是交互式图形的标准格式,只需几行 Python 代码即可带来丰富的用户体验。

使用 Pygal 进行时尚的 Python 绘图

在本介绍中,我们希望重新创建这个多条形图,它代表了 1966 年至 2020 年的英国选举结果

Pygal plot

在我们进一步深入之前,请注意您可能需要调整您的 Python 环境才能运行此代码,包括以下内容。

  • 运行最新版本的 Python(适用于 LinuxMacWindows 的说明)
  • 验证您正在运行的 Python 版本与这些库兼容

数据在线可用,可以使用 pandas 导入

import pandas as pd
df = pd.read_csv('https://anvil.works/blog/img/plotting-in-python/uk-election-results.csv') 

现在我们准备好了。数据看起来像这样

        year  conservative  labour  liberal  others
0       1966           253     364       12       1
1       1970           330     287        6       7
2   Feb 1974           297     301       14      18
..       ...           ...     ...      ...     ...
12      2015           330     232        8      80
13      2017           317     262       12      59
14      2019           365     202       11      72

 

在 Pygal 中绘制此图以我发现易于阅读的方式构建。首先,我们定义样式对象,以便简化我们的条形图定义。然后,我们将自定义样式以及其他元数据传递给 Bar 对象

import pygal
from pygal.style import Style

custom_style = Style(
    colors=('#0343df', '#e50000', '#ffff14', '#929591'),
    font_family='Roboto,Helvetica,Arial,sans-serif',
    background='transparent',
    label_font_size=14,
)

c = pygal.Bar(
    title="UK Election Results",
    style=custom_style,
    y_title='Seats',
    width=1200,
    x_label_rotation=270,
)

然后,我们将数据 addBar 对象中

c.add('Conservative', df['conservative'])
c.add('Labour', df['labour'])
c.add('Liberal', df['liberal'])
c.add('Others', df['others'])

c.x_labels = df['year']

最后,我们将绘图保存为 SVG 文件

c.render_to_file('pygal.svg')

结果是您可以在此 gif 中看到的交互式 SVG 绘图

The Python pygal library can generate rich SVG files as seen here

非常简单,并且效果美观。

结论

Python 中的一些绘图选项需要非常详细地构建每个对象,而 Pygal 从一开始就为您提供了该功能。如果您手头有数据,并且想要制作一个干净、美观且简单的绘图以进行用户交互,请试用 Pygal。您可以在 Anvil 上交互式运行此代码(需要帐户)或使用 此开源运行时 本地运行。

---

本文基于 Anvil 博客上的 Plotting in Pygal,并经许可重复使用。

接下来阅读什么
User profile image.
Shaun 通过模拟世界最大激光系统中的燃烧聚变等离子体,认真地开始了编程。他爱上了 Python 作为数据分析工具,并且从未回头。现在他想把一切都变成 Python。

贡献者

1 条评论

太棒了!!我肯定会看看这些算法,因为我正在使用 Java/Kotlin 创建一些图表。还使用 https://easings.net/#easeOutQuad 使动画更流畅。你试过吗?

Creative Commons License本作品根据 Creative Commons Attribution-Share Alike 4.0 International License 获得许可。
© . All rights reserved.