Python SVG Chart Generator (pysvgchart)
=======================================
A Python package for creating and rendering SVG charts, including line
charts, axes, legends, and text labels. This package supports both
simple and complex chart structures and is highly customisable for
various types of visualisations.
Why did I make this project
---------------------------
This project is designed to produce charts that are easily embedded into python web applications (or other web applications) with minimum fuss.
Many charting libraries for the web rely on JavaScript-driven client-side rendering, often requiring an intermediate
canvas before producing a polished visual. On the other hand, popular python based charting libraries focus on
image-based rendering. Such images are rigid and intractable once embedded into web applications and detailed
customisation is impossible. Although some libraries do generate resolution independent output
it is very difficult to customise.
This package takes a different approach: it generates clean, standalone SVG charts
entirely within Python that can be immediately embedded into a web application. By leveraging SVG’s inherent scalability
and styling flexibility, it eliminates the need for JavaScript dependencies, client-side rendering, or post-processing
steps. The result is a lightweight, backend-friendly solution for producing high-quality, resolution-independent
charts without sacrificing control or maintainability.
Every chart element is designed to be easily modified, giving developers precise control over appearance and structure.
As such, all of the lower level elements are accessible via properties of the charts.
Installation
------------
.. code:: bash
pip install pysvgchart
Alternatively, you can clone this repository and install it locally:
.. code:: bash
git clone https://github.com/arowley-ai/py-svg-chart.git
cd py-svg-chart
pip install .
Usage
-----
Usage depends on which chart you had in mind but each one follows similar principles.
Simple donut chart
^^^^^^^^^^^^^^^^^^
A simple donut chart:
.. code:: python
import pysvgchart as psc
values = [11.3, 20, 30, 40]
donut_chart = psc.DonutChart(values)
svg_string = donut_chart.render()
.. image:: https://raw.githubusercontent.com/arowley-ai/py-svg-chart/refs/heads/main/showcase/donut.svg
:alt: Simple donut chart example
:width: 200px
Donut chart hovers
^^^^^^^^^^^^^^^^^^
The donut is nice but a little boring. To make it a bit more interesting, lets add interactive hover
effects. These effects can be added to any base elements but I thought you'd mostly use it for data labels.
.. code:: python
def hover_modifier(position, name, value, chart_total):
text_styles = {'alignment-baseline': 'middle', 'text-anchor': 'middle'}
return [
psc.Text(x=position.x, y=position.y-10, content=name, styles=text_styles),
psc.Text(x=position.x, y=position.y+10, content="{:.2%}".format(value/chart_total), styles=text_styles)
]
values = [11.3, 20, 30, 40]
names = ['Apples', 'Bananas', 'Cherries', 'Durians']
donut_chart = psc.DonutChart(values, names)
donut_chart.add_hover_modifier(hover_modifier)
donut_chart.render_with_all_styles()
`Here <https://raw.githubusercontent.com/arowley-ai/py-svg-chart/refs/heads/main/showcase/donut_hover.svg>`_ is the output of this code.
In order to get the hover modifiers to display successfully you will need to either render the svg with styles
or include the relevant css separately
Simple line chart
^^^^^^^^^^^^^^^^^
Create a simple line chart:
.. code:: python
import pysvgchart as psc
x_values = list(range(100))
y_values = [4000]
for i in range(99):
y_values.append(y_values[-1] + 100 * random.randint(0, 1))
line_chart = psc.SimpleLineChart(
x_values=x_values,
y_values=[y_values, [1000 + y for y in y_values]],
y_names=['predicted', 'actual'],
x_max_ticks=20,
y_zero=True,
)
line_chart.add_grids(minor_y_ticks=4, minor_x_ticks=4)
line_chart.add_legend()
svg_string = line_chart.render()
.. image:: https://raw.githubusercontent.com/arowley-ai/py-svg-chart/refs/heads/main/showcase/line.svg
:alt: Simple line chart example
More stylised example
^^^^^^^^^^^^^^^^^^^^^
Here's a heavily customised line chart example
.. code:: python
import pysvgchart as psc
def y_labels(num):
num = float('{:.3g}'.format(num))
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
rtn = '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude])
return rtn.replace('.00', '').replace('.0', '')
def x_labels(date):
return date.strftime('%b')
dates = [dt.date.today() - dt.timedelta(days=i) for i in range(500) if (dt.date.today() + dt.timedelta(days=i)).weekday() == 0][::-1]
actual = [(1 + math.sin(d.timetuple().tm_yday / 183 * math.pi)) * 50000 + 1000 * i + random.randint(-10000, 10000) for i, d in enumerate(dates)]
expected = [a + random.randint(-10000, 10000) for a in actual]
line_chart = psc.SimpleLineChart(x_values=dates, y_values=[actual, expected], y_names=['Actual sales', 'Predicted sales'], x_max_ticks=30, x_label_format=x_labels, y_label_format=y_labels, width=1200)
line_chart.series['Actual sales'].styles = {'stroke': "#DB7D33", 'stroke-width': '3'}
line_chart.series['Predicted sales'].styles = {'stroke': '#2D2D2D', 'stroke-width': '3', 'stroke-dasharray': '4,4'}
line_chart.add_legend(x=700, element_x=200, line_length=35, line_text_gap=20)
line_chart.add_y_grid(minor_ticks=0, major_grid_style={'stroke': '#E9E9DE'})
line_chart.x_axis.tick_lines, line_chart.y_axis.tick_lines = [], []
line_chart.x_axis.axis_line = None
line_chart.y_axis.axis_line.styles['stroke'] = '#E9E9DE'
line_end = line_chart.legend.lines[0].end
act_styles = {'fill': '#FFFFFF', 'stroke': '#DB7D33', 'stroke-width': '3'}
line_chart.add_custom_element(psc.Circle(x=line_end.x, y=line_end.y, radius=4, styles=act_styles))
line_end = line_chart.legend.lines[1].end
pred_styles = {'fill': '#2D2D2D', 'stroke': '#2D2D2D', 'stroke-width': '3'}
line_chart.add_custom_element(psc.Circle(x=line_end.x, y=line_end.y, radius=4, styles=pred_styles))
for limit, tick in zip(line_chart.x_axis.scale.ticks, line_chart.x_axis.tick_texts):
if tick.content == 'Jan':
line_chart.add_custom_element(psc.Text(x=tick.position.x, y=tick.position.y + 15, content=str(limit.year), styles=tick.styles))
def hover_modifier(position, x_value, y_value, series_name, styles):
text_styles = {'alignment-baseline': 'middle', 'text-anchor': 'middle'}
params = {'styles': text_styles, 'classes': ['psc-hover-data']}
return [
psc.Circle(x=position.x, y=position.y, radius=3, classes=['psc-hover-data'], styles=styles),
psc.Text(x=position.x, y=position.y - 10, content=str(x_value), **params),
psc.Text(x=position.x, y=position.y - 30, content="{:,.0f}".format(y_value), **params),
psc.Text(x=position.x, y=position.y - 50, content=series_name, **params)
]
line_chart.add_hover_modifier(hover_modifier, radius=5)
line_chart.render_with_all_styles()
.. image:: https://raw.githubusercontent.com/arowley-ai/py-svg-chart/refs/heads/main/showcase/detailed.svg
:alt: Complex line chart example
`View <https://raw.githubusercontent.com/arowley-ai/py-svg-chart/refs/heads/main/showcase/detailed.svg>`_ with hover effects
Contributing
------------
We welcome contributions! If you’d like to contribute to the project,
please follow these steps:
- Fork this repository.
- Optionally, create a new branch (eg. git checkout -b feature-branch).
- Commit your changes (git commit -am ‘Add feature’).
- Push to the branch (eg. git push origin feature-branch).
- Open a pull request.
Created a neat chart?
---------------------
All of the charts in the showcase folder are generated by pytest. If you create something neat that you'd
like to share then see if it can be added to the test suite and it will be generated alongside other
showcase examples.
License
-------
This project is licensed under the MIT License - see the LICENSE file
for details.
Raw data
{
"_id": null,
"home_page": "https://github.com/arowley-ai/py-svg-chart",
"name": "pysvgchart",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.10",
"maintainer_email": null,
"keywords": "pysvgchart",
"author": "Alex Rowley",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/12/21/15c80ab88c2a3161e73c22a5d834669ef469f9c51794e11159c45dd7ef34/pysvgchart-0.5.2.tar.gz",
"platform": null,
"description": "Python SVG Chart Generator (pysvgchart)\n=======================================\n\nA Python package for creating and rendering SVG charts, including line\ncharts, axes, legends, and text labels. This package supports both\nsimple and complex chart structures and is highly customisable for\nvarious types of visualisations.\n\nWhy did I make this project\n---------------------------\nThis project is designed to produce charts that are easily embedded into python web applications (or other web applications) with minimum fuss.\n\nMany charting libraries for the web rely on JavaScript-driven client-side rendering, often requiring an intermediate\ncanvas before producing a polished visual. On the other hand, popular python based charting libraries focus on\nimage-based rendering. Such images are rigid and intractable once embedded into web applications and detailed\ncustomisation is impossible. Although some libraries do generate resolution independent output\nit is very difficult to customise.\n\n\nThis package takes a different approach: it generates clean, standalone SVG charts\nentirely within Python that can be immediately embedded into a web application. By leveraging SVG\u2019s inherent scalability\nand styling flexibility, it eliminates the need for JavaScript dependencies, client-side rendering, or post-processing\nsteps. The result is a lightweight, backend-friendly solution for producing high-quality, resolution-independent\ncharts without sacrificing control or maintainability.\n\nEvery chart element is designed to be easily modified, giving developers precise control over appearance and structure.\nAs such, all of the lower level elements are accessible via properties of the charts.\n\nInstallation\n------------\n\n.. code:: bash\n\n pip install pysvgchart\n\nAlternatively, you can clone this repository and install it locally:\n\n.. code:: bash\n\n git clone https://github.com/arowley-ai/py-svg-chart.git\n cd py-svg-chart\n pip install .\n\nUsage\n-----\n\nUsage depends on which chart you had in mind but each one follows similar principles.\n\nSimple donut chart\n^^^^^^^^^^^^^^^^^^\n\nA simple donut chart:\n\n.. code:: python\n\n import pysvgchart as psc\n\n values = [11.3, 20, 30, 40]\n donut_chart = psc.DonutChart(values)\n svg_string = donut_chart.render()\n\n.. image:: https://raw.githubusercontent.com/arowley-ai/py-svg-chart/refs/heads/main/showcase/donut.svg\n :alt: Simple donut chart example\n :width: 200px\n\n\nDonut chart hovers\n^^^^^^^^^^^^^^^^^^\nThe donut is nice but a little boring. To make it a bit more interesting, lets add interactive hover\neffects. These effects can be added to any base elements but I thought you'd mostly use it for data labels.\n\n.. code:: python\n\n def hover_modifier(position, name, value, chart_total):\n text_styles = {'alignment-baseline': 'middle', 'text-anchor': 'middle'}\n return [\n psc.Text(x=position.x, y=position.y-10, content=name, styles=text_styles),\n psc.Text(x=position.x, y=position.y+10, content=\"{:.2%}\".format(value/chart_total), styles=text_styles)\n ]\n\n values = [11.3, 20, 30, 40]\n names = ['Apples', 'Bananas', 'Cherries', 'Durians']\n donut_chart = psc.DonutChart(values, names)\n donut_chart.add_hover_modifier(hover_modifier)\n donut_chart.render_with_all_styles()\n\n`Here <https://raw.githubusercontent.com/arowley-ai/py-svg-chart/refs/heads/main/showcase/donut_hover.svg>`_ is the output of this code.\nIn order to get the hover modifiers to display successfully you will need to either render the svg with styles\nor include the relevant css separately\n\nSimple line chart\n^^^^^^^^^^^^^^^^^\n\nCreate a simple line chart:\n\n.. code:: python\n\n import pysvgchart as psc\n\n x_values = list(range(100))\n y_values = [4000]\n for i in range(99):\n y_values.append(y_values[-1] + 100 * random.randint(0, 1))\n\n line_chart = psc.SimpleLineChart(\n x_values=x_values,\n y_values=[y_values, [1000 + y for y in y_values]],\n y_names=['predicted', 'actual'],\n x_max_ticks=20,\n y_zero=True,\n )\n line_chart.add_grids(minor_y_ticks=4, minor_x_ticks=4)\n line_chart.add_legend()\n\n svg_string = line_chart.render()\n\n.. image:: https://raw.githubusercontent.com/arowley-ai/py-svg-chart/refs/heads/main/showcase/line.svg\n :alt: Simple line chart example\n\nMore stylised example\n^^^^^^^^^^^^^^^^^^^^^\n\nHere's a heavily customised line chart example\n\n.. code:: python\n\n import pysvgchart as psc\n\n def y_labels(num):\n num = float('{:.3g}'.format(num))\n magnitude = 0\n while abs(num) >= 1000:\n magnitude += 1\n num /= 1000.0\n rtn = '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude])\n return rtn.replace('.00', '').replace('.0', '')\n\n def x_labels(date):\n return date.strftime('%b')\n\n dates = [dt.date.today() - dt.timedelta(days=i) for i in range(500) if (dt.date.today() + dt.timedelta(days=i)).weekday() == 0][::-1]\n actual = [(1 + math.sin(d.timetuple().tm_yday / 183 * math.pi)) * 50000 + 1000 * i + random.randint(-10000, 10000) for i, d in enumerate(dates)]\n expected = [a + random.randint(-10000, 10000) for a in actual]\n line_chart = psc.SimpleLineChart(x_values=dates, y_values=[actual, expected], y_names=['Actual sales', 'Predicted sales'], x_max_ticks=30, x_label_format=x_labels, y_label_format=y_labels, width=1200)\n line_chart.series['Actual sales'].styles = {'stroke': \"#DB7D33\", 'stroke-width': '3'}\n line_chart.series['Predicted sales'].styles = {'stroke': '#2D2D2D', 'stroke-width': '3', 'stroke-dasharray': '4,4'}\n line_chart.add_legend(x=700, element_x=200, line_length=35, line_text_gap=20)\n line_chart.add_y_grid(minor_ticks=0, major_grid_style={'stroke': '#E9E9DE'})\n line_chart.x_axis.tick_lines, line_chart.y_axis.tick_lines = [], []\n line_chart.x_axis.axis_line = None\n line_chart.y_axis.axis_line.styles['stroke'] = '#E9E9DE'\n line_end = line_chart.legend.lines[0].end\n act_styles = {'fill': '#FFFFFF', 'stroke': '#DB7D33', 'stroke-width': '3'}\n line_chart.add_custom_element(psc.Circle(x=line_end.x, y=line_end.y, radius=4, styles=act_styles))\n line_end = line_chart.legend.lines[1].end\n pred_styles = {'fill': '#2D2D2D', 'stroke': '#2D2D2D', 'stroke-width': '3'}\n line_chart.add_custom_element(psc.Circle(x=line_end.x, y=line_end.y, radius=4, styles=pred_styles))\n for limit, tick in zip(line_chart.x_axis.scale.ticks, line_chart.x_axis.tick_texts):\n if tick.content == 'Jan':\n line_chart.add_custom_element(psc.Text(x=tick.position.x, y=tick.position.y + 15, content=str(limit.year), styles=tick.styles))\n\n def hover_modifier(position, x_value, y_value, series_name, styles):\n text_styles = {'alignment-baseline': 'middle', 'text-anchor': 'middle'}\n params = {'styles': text_styles, 'classes': ['psc-hover-data']}\n return [\n psc.Circle(x=position.x, y=position.y, radius=3, classes=['psc-hover-data'], styles=styles),\n psc.Text(x=position.x, y=position.y - 10, content=str(x_value), **params),\n psc.Text(x=position.x, y=position.y - 30, content=\"{:,.0f}\".format(y_value), **params),\n psc.Text(x=position.x, y=position.y - 50, content=series_name, **params)\n ]\n\n line_chart.add_hover_modifier(hover_modifier, radius=5)\n line_chart.render_with_all_styles()\n\n.. image:: https://raw.githubusercontent.com/arowley-ai/py-svg-chart/refs/heads/main/showcase/detailed.svg\n :alt: Complex line chart example\n\n`View <https://raw.githubusercontent.com/arowley-ai/py-svg-chart/refs/heads/main/showcase/detailed.svg>`_ with hover effects\n\n\n\nContributing\n------------\n\nWe welcome contributions! If you\u2019d like to contribute to the project,\nplease follow these steps:\n\n- Fork this repository.\n- Optionally, create a new branch (eg. git checkout -b feature-branch).\n- Commit your changes (git commit -am \u2018Add feature\u2019).\n- Push to the branch (eg. git push origin feature-branch).\n- Open a pull request.\n\nCreated a neat chart?\n---------------------\n\nAll of the charts in the showcase folder are generated by pytest. If you create something neat that you'd\nlike to share then see if it can be added to the test suite and it will be generated alongside other\nshowcase examples.\n\n\nLicense\n-------\n\nThis project is licensed under the MIT License - see the LICENSE file\nfor details.\n",
"bugtrack_url": null,
"license": "MIT license",
"summary": "Creates svg based charts in python",
"version": "0.5.2",
"project_urls": {
"Homepage": "https://github.com/arowley-ai/py-svg-chart"
},
"split_keywords": [
"pysvgchart"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "24ed0646962cb0b45f37ce6a290a39119a3ad218003cb93444c964f3fa8f363d",
"md5": "8213d61411ad3c9be9c985e02518902f",
"sha256": "8d530d0fc6a4f303ede01507c4540dbf03c84290a9872fff3a69ef3b3bda1ce2"
},
"downloads": -1,
"filename": "pysvgchart-0.5.2-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "8213d61411ad3c9be9c985e02518902f",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": ">=3.10",
"size": 21401,
"upload_time": "2025-07-10T04:55:16",
"upload_time_iso_8601": "2025-07-10T04:55:16.055569Z",
"url": "https://files.pythonhosted.org/packages/24/ed/0646962cb0b45f37ce6a290a39119a3ad218003cb93444c964f3fa8f363d/pysvgchart-0.5.2-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "122115c80ab88c2a3161e73c22a5d834669ef469f9c51794e11159c45dd7ef34",
"md5": "488ef5558fa744407517f39d51621c1b",
"sha256": "b49f2f114e40536a3f39587ba8c79dde15005ae712afe1d79726153787a455e0"
},
"downloads": -1,
"filename": "pysvgchart-0.5.2.tar.gz",
"has_sig": false,
"md5_digest": "488ef5558fa744407517f39d51621c1b",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.10",
"size": 23313,
"upload_time": "2025-07-10T04:55:17",
"upload_time_iso_8601": "2025-07-10T04:55:17.258423Z",
"url": "https://files.pythonhosted.org/packages/12/21/15c80ab88c2a3161e73c22a5d834669ef469f9c51794e11159c45dd7ef34/pysvgchart-0.5.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-10 04:55:17",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "arowley-ai",
"github_project": "py-svg-chart",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "pysvgchart"
}