pyx-project / pyx Goto Github PK
View Code? Open in Web Editor NEWRepository of PyX, a Python package for the creation of PostScript, PDF, and SVG files.
Home Page: https://pyx-project.org/
License: GNU General Public License v2.0
Repository of PyX, a Python package for the creation of PostScript, PDF, and SVG files.
Home Page: https://pyx-project.org/
License: GNU General Public License v2.0
When I run
from pyx import canvas
can = canvas.canvas([canvas.clip])
I get this error
Traceback (most recent call last):
can = canvas.canvas([canvas.clip])
File "/usr/local/lib/python3.6/dist-packages/pyx/canvas.py", line 135, in __init__
attr.checkattrs(attrs, [trafo.trafo_pt, clip, style.style])
File "/usr/local/lib/python3.6/dist-packages/pyx/attr.py", line 56, in checkattrs
raise TypeError("instance %r not allowed" % attrs[len(getattrs(attrs, allowedclasses))])
TypeError: instance <class 'pyx.canvas.clip'> not allowed
Pyx version 0.15
Python 3.6
https://github.com/algolia/docsearch
It's a proprietary service, but provides free access for open source software projects.
What do you think?
Personally I think Algolia DocSearch is more snappy and has more convenient keyboard shortcut & result preview. You can try it on https://tikz.dev (press Ctrl+K then type something in)
Also it would reduce the workload on the hosting server (currently Sphinx search feature is run on the server) (I don't know what the server is hosted on).
If I draw a picture and want to crop its edges, is there a related function? We are expecting a reply!
Hello,
I am trying to run the following basic example:
from pyx import canvas, path, deco
rect = path.rect(0, 0, 5, 2)
arc = path.arc(0, 0, 1, 30, 45)
canvas = canvas.canvas()
canvas.stroke(rect, [deco.earrow.small])
canvas.stroke(arc)
canvas.writePDFfile()
When I run it:
python3 example2.py
I get the following error:
C:\Users\PC\AppData\Local\Temp\pyx>python example2.py
Traceback (most recent call last):
File "example2.py", line 10, in <module>
canvas.writePDFfile()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyx\canvas.py", line 50, in wrappedindocument
return method(d, file, **write_kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyx\document.py", line 193, in writePDFfile
pdfwriter.PDFwriter(self, f, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyx\pdfwriter.py", line 329, in __init__
catalog = PDFcatalog(document, self, registry)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyx\pdfwriter.py", line 143, in __init__
self.PDFpages = PDFpages(document, writer, registry)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyx\pdfwriter.py", line 202, in __init__
page = PDFpage(page, pageno, self, writer, registry)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyx\pdfwriter.py", line 236, in __init__
self.PDFcontent = PDFcontent(page, writer, self.pageregistry)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyx\pdfwriter.py", line 268, in __init__
page.processPDF(contentfile, awriter, acontext, registry, self.bbox)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyx\document.py", line 135, in processPDF
self._process("processPDF", *args)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyx\document.py", line 78, in _process
bbox.set(self.canvas.bbox()) # this bbox is not accurate
File "C:\ProgramData\Anaconda3\lib\site-packages\pyx\canvas.py", line 179, in bbox
obbox += cmd.bbox()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyx\deco.py", line 101, in bbox
pathbbox = self.path.bbox()
AttributeError: 'arc' object has no attribute 'bbox'
When trying to create a parallel circle, the parallel deformer fails for when the radius should be decreased.
import pyx
# works
arcargs = (0.0, 0.0, 1.0, 90, 449)
# does not work
arcargs = (0.0, 0.0, 1.0, 90, 450)
og_path = pyx.path.path(pyx.path.arc(*arcargs))
defo_path = pyx.deformer.parallel(0.1).deform(og_path)
c = pyx.canvas.canvas()
c.stroke(og_path)
c.stroke(defo_path, [pyx.color.rgb.red])
c.writePDFfile()
When I use
text.set(text.UnicodeEngine)
got error
Traceback (most recent call last):
File "d:/MyFiles/LearnPython/pyx-unicode.py", line 3, in <module>
text.set(text.UnicodeEngine)
File "C:\Python36-32bit\lib\site-packages\pyx\text.py", line 1814, in set
defaulttextengine = engine(*args, **kwargs)
File "C:\Python36-32bit\lib\site-packages\pyx\text.py", line 1708, in __init__
with config.open(fontname, [config.format.type1]) as f:
raise IOError("Could not locate the file '%s'." % filename)
OSError: Could not locate the file 'cmr10'.
How to fix it?
I would like to know if it is possible to create gridded axes in 3d-graphs like in here. If not, this would be a great feature to enhance quality of 3d-graphs.
How do I change the tick style on all borders?
I use
axispainter = pyx.graph.axis.painter.regular(
tickattrs=[
pyx.attr.changelist(
[pyx.style.linewidth.THIn, # Main ticks on x and y axis
pyx.style.linewidth.THIn # Minor thicks on x and y axis
])])
but this does only change the ticks on the primary x and y axis (bottom and left). Even if I add more pyx.style.linewidth.THIn
to oyx.attr.changelist([...])
, it does not change the ticks on the right and top axis …
In the LaTeX log, characters appearing in the TeX input are represented using the fontenc
. This can ultimately lead to a UnicodeDecodeError
as in the following minimal example:
from pyx import canvas, text
text.set(text.LatexRunner, texenc="utf-8")
text.preamble(r"""\usepackage[T1]{fontenc}
\usepackage[utf8x]{inputenc}""")
c = canvas.canvas()
c.text(0, 0, r'foo föo föo f\"oo f\"oo', [text.parbox(2)])
c.writePDFfile()
In the LaTeX log, the umlaut ö
will be represented as byte 0xf6
which cannot be interpreted as UTF-8 encoded character. The problem arises independently of whether the umlaut in the input is given in UTF-8 or in TeX code (\"o
).
grozin@bilbo ~/tmp/pyx-master/test/functional $ python test_text.py
ignoring special 'Warning: missing glyph `Gamma''
ignoring special 'Warning: missing glyph `Gamma''
ignoring special 'Warning: missing glyph `Gamma''
ignoring special 'Warning: missing glyph `Gamma''
Traceback (most recent call last):
File "/home/grozin/tmp/pyx-master/test/functional/test_text.py", line 117, in <module>
ue_pfm = text.UnicodeEngine(metric=text.UnicodeEngine.pfm_metric)
AttributeError: type object 'UnicodeEngine' has no attribute 'pfm_metric'
Indeed, class UnicodeEngine
in pyx/text.py
has only the attributes
>>> dir(pyx.text.UnicodeEngine)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'preamble', 'reset', 'text', 'text_pt']
I had to comment out 2 lines in test/functional/test_text.py
:
ue_pfm = text.UnicodeEngine(metric=text.UnicodeEngine.pfm_metric)
c.insert(ue_pfm.text(10, 8, "UnicodeEngine output (PFM)"))
then tests run successfully.
Using this occasion, I'd like to add 2 points:
pyx/text.py
,r = self._wait(self._received.wait, self._received.isSet)
isSet
is deprecated, and should be replaced by is_set
.
manual/colorname.py
and manual/gradientname.py
,lines = imp.find_module("color", pyx.__path__)[0].readlines()
imp
is deprecated, and importlib
should be used instead. However, there is no exact equivalent of imp.find_module
, and some thought is needed. I have not done it.
I think this class: https://github.com/mjg/PyX/blob/ea656fc3771004e5c88a60aabdbdf0a66452bfe1/pyx/style.py#L162
Could benefit from implementing equality comparisons.
Example use case, if style == linestyle.dashed: set_linewidth(0.001)
Hi,
Thank you for contributing/maintaining a nice package.
I'm just wondering that if I want to set a canvas with width = 1000mm and height = 800mm with 20mm margin for all surrounding sides (i.e., top, left, right, and bottom have 20mm white space), is there any similar example to do this?
I found Page APIs from https://pyx-project.org/manual/document.html but it is a bit difficult to follow for a new pyx user.
Thanks again!.
Best regards
I was trying to run the "hello.py" script, unmodified, just dragged from example folder to the root folder so that it would run, but I came across an error:
did i screw up anything?
File "c:/Users/x/Desktop/pyx-master/hello.py", line 4, in <module>
c.text(0, 0, "Hello, world!")
File "c:\Users\x\Desktop\pyx-master\pyx\canvas.py", line 409, in text
return self.insert(self.textengine.text(x, y, atext, *args, **kwargs))
File "c:\Users\x\Desktop\pyx-master\pyx\text.py", line 1454, in wrapped
return f(self, *args, **kwargs)
File "c:\Users\x\Desktop\pyx-master\pyx\text.py", line 1490, in text
return self.instance.text(*args, **kwargs)
File "c:\Users\x\Desktop\pyx-master\pyx\text.py", line 1330, in text
return self.text_pt(unit.topt(x), unit.topt(y), *args, **kwargs)
File "c:\Users\x\Desktop\pyx-master\pyx\text.py", line 1304, in text_pt
left_pt, right_pt, height_pt, depth_pt = self.do_typeset(expr, self.texmessages_run_default + self.texmessages_run + texmessages)
File "c:\Users\x\Desktop\pyx-master\pyx\text.py", line 1221, in do_typeset
self.do_start()
File "c:\Users\x\Desktop\pyx-master\pyx\text.py", line 1370, in do_start
super().do_start()
File "c:\Users\x\Desktop\pyx-master\pyx\text.py", line 1176, in do_start
self.popen = config.Popen(cmd, stdin=config.PIPE, stdout=config.PIPE, stderr=config.STDOUT, bufsize=0)
File "c:\Users\x\Desktop\pyx-master\pyx\config.py", line 218, in Popen
return subprocess.Popen(cmd, *args, **kwargs)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\subprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "c:\Users\x\Desktop\pyx-master\pyx\text.py", line 1035, in _cleanup
self.do_finish(cleanup=False)
File "c:\Users\x\Desktop\pyx-master\pyx\text.py", line 1235, in do_finish
self.go_finish()
File "c:\Users\x\Desktop\pyx-master\pyx\text.py", line 1364, in go_finish
self._execute("\\end%\n", self.texmessages_end_default + self.texmessages_end, STATE_TYPESET, STATE_DONE)
File "c:\Users\x\Desktop\pyx-master\pyx\text.py", line 1078, in _execute
self.texoutput.expect(None)
AttributeError: 'SingleTexEngine' object has no attribute 'texoutput'```
In the output of the following code, the height of the ticklabel "0" of the x-axis is strange.
import sys, os
from pyx import *
import numpy as np
text.set(engine=text.LatexEngine)
text.preamble(r"\usepackage{cmbright}")
w = 6
h = 6
c = canvas.canvas()
g = c.insert(graph.graphxy(height=h, width=w,
x=graph.axis.linear(min=0, max=5, title="$x$"),
y=graph.axis.linear(title="$y$")))
g.plot(graph.data.function("y(x)=cos(x)"),
[graph.style.line()])
c.writePDFfile()
I use PyX 0.15 on Archlinux, and my version of Python is 3.9.6.
This does not happen if :
graph.axis.linear
, and put them indata.function
instead.engine=text.LatexEngine
by text.LatexRunner
.It would make sense for distributions to set a default font search location to packaged amsfonts. Currently it seems hard to set that default value.
Would it be appropriate to enable recursivedir
by default and point it to the location?
I want to output 3D PDF,but the 3d graph pdf is 2d.
so how to use Pyx to write 3d pdf?
PyX currently fails quite badly when added to a PyOxidizer project, initially because of indygreg/PyOxidizer#69 .
It would be a big start if the use of __file__
can be removed, or its absence ignored, or at least delayed and only used when necessary, so that the majority of PyX can work while other parts remain broken.
The initial problem I encountered was that pyxrc
is always loaded from local
, so any pyxrc
stored inside the binary is not used.
In LaTeX, there is a feature savepos
in zref
that allows saving the absolute location of something on a page (needs another compilation pass).
Which allows implementing something like How can I make arrow from parts of a formula in Asymptote? (or: measure the width of a label, get anchor around a label) - TeX - LaTeX Stack Exchange .
Would the same thing be possible in PyX? (I think it should be possible by using the engine primitives and write to file etc. or just write to stdout and make PyX parse the output somehow)
Dear Jörg, Dear André,
I stumbled upon some strange behavior when the output is SVG. Consider this
simple example which draws a rectangle and writes some text:
from pyx import *
c = canvas.canvas()
c.stroke(path.rect(0, 0, 1, 1), [deco.filled([color.rgb.red])])
c.text(2,0, "Hello world")
c.writePDFfile()
c.writeSVGfile()
The PDF file has the expected output: A red rectangle with black border, and
black text. However, the font color of the "Hello wold" text is not black but
red when using the SVG output (see also attachement).
For me this is currently not a big issue. As a workaround I set in my script
the font color explicitly to black. But I guess that SVG and PDF output should
look the same, so there is probably a problem somewhere.
I am using Python 3.6.5 from the Anaconda distribution and PyX in version 0.14.1.
Best wishes,
--Michael
Attachement:
output.zip
I hope this is the right place for the question / issue I have, I apologize if it isn't (In that case, what would be the correct place?).
I am currently learning PyX and going through the documentation. I can't however get the methods path.path.curveradius and path.path.range to work. E.g. when I create an arc
called pth
pth = path.path(path.arc(0, 0, 1, 0, 120))
and ask for its range
pth.range()
an error is returned
AttributeError: 'path' object has no attribute 'range'
Similarly for asking the curveradius
at the beginning of the path
pth.curveradius(0)
results in
'path' object has no attribute 'curveradius'
I've looked into the source code of the path module path.py and couldn't find the methods though could find other methods listed in the documentation.
Also, I noticed that in the release announcement op PyX 0.13 that curveradius
has been removed from the normpath
module. Could it be that the method has been removed in the past but that this change was not updated in the documentation?
Thank you in advance for an answer.
Alwin
The docs very skilfully show how to add a path that is known at "compile time", but since the input to path.path
it's not immediately obvious how to create a path from say, a list of points.
I would like to suggest adding an example like that, or editing the current example, to show how one might deal with user generated points, or with points read from a file.
Code:
c.text(
CODE_X_POS[page_id_pos] + TEXT_X_OFFSET,
CODE_Y_POS[page_id_pos] + TEXT_Y_OFFSET,
"{} ({}/{})".format(ASC_FILE, bc + 1, len(CODE_BLOCKS)),
)
Error:
Traceback (most recent call last):
File "/home/adil/Projects/paperbackup/main.py", line 76, in <module>
c.text(
File "/home/adil/.local/lib/python3.9/site-packages/pyx/canvas.py", line 409, in text
return self.insert(self.textengine.text(x, y, atext, *args, **kwargs))
File "/home/adil/.local/lib/python3.9/site-packages/pyx/text.py", line 1454, in wrapped
return f(self, *args, **kwargs)
File "/home/adil/.local/lib/python3.9/site-packages/pyx/text.py", line 1490, in text
return self.instance.text(*args, **kwargs)
File "/home/adil/.local/lib/python3.9/site-packages/pyx/text.py", line 1330, in text
return self.text_pt(unit.topt(x), unit.topt(y), *args, **kwargs)
File "/home/adil/.local/lib/python3.9/site-packages/pyx/text.py", line 1304, in text_pt
left_pt, right_pt, height_pt, depth_pt = self.do_typeset(expr, self.texmessages_run_default + self.texmessages_run + texmessages)
File "/home/adil/.local/lib/python3.9/site-packages/pyx/text.py", line 1221, in do_typeset
self.do_start()
File "/home/adil/.local/lib/python3.9/site-packages/pyx/text.py", line 1370, in do_start
super().do_start()
File "/home/adil/.local/lib/python3.9/site-packages/pyx/text.py", line 1176, in do_start
self.popen = config.Popen(cmd, stdin=config.PIPE, stdout=config.PIPE, stderr=config.STDOUT, bufsize=0)
File "/home/adil/.local/lib/python3.9/site-packages/pyx/config.py", line 218, in Popen
return subprocess.Popen(cmd, *args, **kwargs)
File "/usr/lib/python3.9/subprocess.py", line 951, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.9/subprocess.py", line 1823, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'tex'
For a long time I have used asymptote for publication quality figures but I've recently started looking for Python alternative. It's great to see that pyx has all the essential functionality to serve as a replacement. Well done, guys!
However, one feature that I miss is the existence of a class for 2d vectors which integrates with the methods for path construction. In asymptote I normally start by defining a number of relevant points on the canvas and then build the paths from these points. And something like
point1 = point0 + voffset*UP + hoffset*LEFT
is simply more readable than
point1x = point0x - hoffset
point1y = point0y + voffset
I'm wondering if you would consider adding a 2D vector class and changing the path construction methods so that the accept 2D vectors rather than x and y coordinates.
I've had a look at the code and I think I understand it well enough to try and implement it myself but since it's a big change to the interface I first wanted to check if you'd be willing to make such a change.
Installing pyx from source within a fresh environment as
python -m pip install -U pip
python -m pip install pyx
yields
DEPRECATION: pyx is being installed using the legacy 'setup.py install' method, because it does not have a 'pyproject.toml' and the 'wheel' package is not installed. pip 23.1 will enforce this behaviour change. A possible replacement is to enable the '--use-pep517' option. Discussion can be found at https://github.com/pypa/pip/issues/8559
Is it possible to change the linewidth
and the linestyle
of grid lines?
My naïve approach does not work
axispainter = pyx.graph.axis.painter.regular(
# Make thin and dashed grid lines for major grid
# No grid lines for sub- and subsubgrid
gridattrs=[
pyx.attr.changelist(
[[pyx.style.linestyle.dashed,
pyx.style.linewidth.THIn],
None,
None])])
Thanks for your help and your great package!!!
pip install PyX
or pip install PyX==0.13
even pip install git+https://github.com/pyx-project/pyx.git@fc66c078727b02693b122ad346b9fa5472e06eb7
, also tried with no-cache-dir
fails to install package and returns No files/directories in /tmp/pip-build-cXIeQt/PyX/pip-egg-info (from PKG-INFO)
the latest version I can install is pyX==0.12
Traceback (most recent call last):
File "fig1.py", line 101, in <module>
c.insert(pyx.epsfile.epsfile(0, 0, "f1a.eps", align="tl"))
File "/shares/Public/xfr/anaconda3/envs/3.8/lib/python3.8/site-packages/pyx/epsfile.py", line 252, in __init__
self.mybbox = _readbbox(epsfile)
File "/shares/Public/xfr/anaconda3/envs/3.8/lib/python3.8/site-packages/pyx/epsfile.py", line 160, in _readbbox
return bbox.bbox_pt(*list(map(int, values)))
ValueError: invalid literal for int() with base 10: b'90.1279302777778'
Fix: change int() to float()
I am trying to render a fracion with pyx:
from pyx import *
from pyx import text
text.set(mode="latex")
text.preamble(r"\usepackage{amssymb}")
text.preamble(r"\usepackage{amsmath}")
c.text(-0.5, 0.1, r"\huge{$\frac{8}{3}$}", [text.halign.boxcenter])
But I am getting an error:
\ProcessPyXBox{\gdef\PyXBoxHAlign{0.50000}\huge{$\frac{8}{3}$}%
}{1}%
\PyXInput{5}%
After parsing the return message from TeX, the following was left:
*
*! Undefined control sequence.
<recently read> \frac
<argument> ...PyXBoxHAlign {0.50000}\huge {$\frac
(cut after 5 lines; use errordetail.full for all output)
The documentation says that the string is passed directly onto the LateX engine, and to my knowledge the engine should be able to handle the frac
command, so I am a bit confused.
I'm seeing an unexpected black bounding box around the canvas when the use c.writePDFfile(parsed.output)
.
However, it doesn't exist when I use c.writeSVGfile(parsed.output)
.
See: apriltag_id0.zip
What might be the reason? How can I fix it?
We should abandon the space parameter in favor of a split parameter. By default it is unset, which means, PyX splits at spaces. You may set it to ";" (probably well known for Windows) or ":" (probably the "right" things for unix systems) and use that for splitting. However, the issue remains, that you need to choose yourself, as it automatically results in the character being not available as part of the content values in the lists.
This should make the whole thing way more intuitive.
Hello,
I would like to create a 2D color gradation plot. In the PyX-examples is the density plot, so somethinig like this. But data points are not evenly distributed. Thus this plot type does not work.
In examples about 3D-plots is the colored surface and in the text you describe: "Skipping the value for the z component will allow you to plot this surface on a two-dimensional graph as well." But I am not able to do this.
Can you please give an example an how to plot a colored surface in a 2D-graph?
Thankyou
Let's look at this code:
from pyx import *
from math import *
c = canvas.canvas()
angles = {"B": 0, "A": 2*pi/3, "C": 2*pi*2/3}
circles={}
for k,v in angles.items():
circles[k] = path.circle(sin(v), cos(v), 1.7)
c.stroke(circles[k])
def intersect(cp1, cp2):
(int1), (int2) = cp1.intersect(cp2)
arch1 = cp1.split(int1)[1]
return arch1
c.stroke(intersect(circles["B"], circles["A"]), [color.rgb.red])
c.stroke(intersect(circles["C"], circles["B"]), [color.rgb.green])
c.stroke(intersect(circles["A"], circles["C"]), [color.rgb.blue])
c.writePDFfile()
As one might expect, it produces this figure
But If I replace the last part with
c.stroke(intersect(circles["A"], circles["B"]), [color.rgb.red])
c.stroke(intersect(circles["B"], circles["C"]), [color.rgb.green])
c.stroke(intersect(circles["C"], circles["A"]), [color.rgb.blue])
the results looks like this.
The way the blue line looks is inconsistent with the rest.
It would be nice to be able to fully reset a canvas (i.e. make it all white again), but it seems there is no method for doing so:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.