I'm trying to use Graphviz fo the decision tree classifier, the code is here.
I expect the output of a diagram but the actual output is this message:
warning, language pdf not recognized, use one of:
dot canon plain plain-ext
dot: option -O unrecognized
warning, language svg not recognized, use one of:
dot canon plain plain-ext
Any help is appreciated
import graphviz
dot_data = tree.export_graphviz(dtc, out_file=None)
graph = graphviz.Source(dot_data)
graph.render("data")
graph
Related
I am using a combination of networkx, pygraphviz and graphviz to create and visualise graphs in python,
However I keep encountering utf-8 encoding errors when writing my dot file from my networkx graph that has greek letters as nodes.
I would like to be able to create dot graphs with nodes such as these: Κύριος, Θεός, Πᾶσα, Μέγας, Νέμεσις but am unable to do so.
Are there any encoding tricks I need to know about?
The example you posted works fine for me (using ipython with python 3.7) when using the correct dot file path.
import networkx as nx
from networkx.drawing.nx_pydot import write_dot
import graphviz as grv
n = "Νέμεσις"
G = nx.Graph()
G.add_node(n)
write_dot(G, 'test.dot')
grv.render('neato', 'svg', 'test.dot')
I'm using networkx (v2.5) for a dependency-analysis problem, and visualizing the data via graphviz / pygraphviz (v1.7) on ubuntu 20.04. The contents of each node (label field) is a code block - so I'd like it LEFT justified. The problem is I can't seem to change the default (CENTER justified).
X/Y: - my specific need is to make a png from a networkx graph where the node text is left-justified - I believe Graphviz/pygraphviz is the best ~trivial way to do so - but any FOSS way to accomplish this would be fine.
I successfully generate a png as desired, via the following simplified code, but the text is all center-justified.
from networkx import DiGraph, nx_agraph
from networkx.drawing.nx_agraph import write_dot
# graph is created via networkx:
graph = DiGraph()
graph.add_edge("node1", "node2")
graph.nodes["node1"]["label"] = get_code_sniped("node1")
# ...
# and converted / output to dot & png via (internally) pygraphviz
write_dot(graph, "/tmp/foo.dot") # appears correctly output
a_graph = nx_agraph.to_agraph(graph)
a_graph.layout(prog="dot")
# attempt to add attrs per defs in
# https://www.graphviz.org/doc/info/attrs.html#d:labeljust
a_graph.graph_attr.update(labeljust="l") # <----- has no effect on output
a_graph.graph_attr.update(nojustify=True) # <-/
a_graph.draw("/tmp/foo.png") # <-- PNG outputs successfully,
# but all node text is CENTER justified
How can I modify the node text (specifically left-justifying it) in the PNG generated from my networkx graph?
it appears there is (undocumented, AFAICT) upstream/native graphviz behavior w.r.t. inheriting graph-level attributes.
setting a_graph.graph_attr.update(... is insufficient, as it is not inherited by child elements. In order to for instance set fontname, the following works:
for node in formattable_graph.iternodes():
node.attr["fontname"] = "Liberation Mono"
also, for text-justification, one can control this on a Per line basis by changing the line ending "\l" (Note: that is two bytes in python as it's not an actual escape char) and "\r" for left and right (respectively).
this will LEFT justify all lines
graph.nodes["node1"]["label"] = """my
node label
with newlines
""".replace("\n", "\l")
I want to make a graph with random node positions but it seems that the "pos" attribute for nodes does nothing. Here is a minimal example:
import graphviz
import pylab
from graphviz import Digraph
g = Digraph('G', filename='ex.gv',format='pdf')
g.attr(size='7')
g.node('1',pos='1,2')
g.node('2',pos='2,3')
g.node('3',pos='0,0')
g.edge('1','2')
g.edge('1','3')
graphviz.Source(g)
Any ideas of how achieve that?
Thanks in advance.
Although not 100% clear in the docs, I think pos is not supported in the dot engine on input. The fdp or neato engines do support pos on input for setting the initial position, and if you end the coordinate specification with '!', the coordinates will not change and thus become the final node position.
Play with a live example at https://beta.observablehq.com/#magjac/placing-graphviz-nodes-in-fixed-positions
This standalone python script generates a pdf with the expected node positions:
#!/usr/bin/python
import graphviz
from graphviz import Digraph
g = Digraph('G', engine="neato", filename='ex.gv',format='pdf')
g.attr(size='7')
g.node('1',pos='1,2!')
g.node('2',pos='2,3!')
g.node('3',pos='0,0!')
g.edge('1','2')
g.edge('1','3')
g.render()
Since SO does not support pdf uploading, here's a png image generated with the same code except format='png':
Without the exclamation marks you get:
Without any pos attributes at all you get a similar (but not exactly the same) result:
I am using networkx to plot graph in python. However, my output is too dense. Is there any ways to sparse the graph? Below is my command in python.Thanks
pos=nx.spring_layout(self.G)
nx.draw_networkx_nodes(self.G,pos)
edge_labels=dict([((u,v,),d['weight'])
for u,v,d in self.G.edges(data=True)])
nx.draw_networkx_labels(self.G,pos, font_size=20,font_family='sans-serif')
nx.draw_networkx_edges(self.G,pos)
plt.axis('off')
#nx.draw_networkx_labels(self.G,pos, font_size=20,font_family='sans-serif')
nx.draw_networkx_edge_labels(self.G,pos,edge_labels=edge_labels)
nx.draw(self.G,pos, edge_cmap=plt.cm.Reds)
plt.show()
You can also try Graphviz via PyDot (I prefer this one) or PyGraphviz.
In case you are interested in a publication-ready result, you can use the toolchain networkx -> pydot + dot -> dot2tex + dot -> dot2texi.sty -> TikZ. Instead of this fragile toolchain, you can alternatively export directly to TikZ with nx2tikz (I've written it, so I'm biased) and use the graph layout algorithms that have been relatively recently added to TikZ.
After I check some information from the documentation here: http://networkx.github.io/documentation/latest/reference/drawing.html#module-networkx.drawing.layout
I changed the format of layout to
pos=nx.circular_layout(self.G, scale=5)
and it works!
When I try to save a python figure as PostScript ,When using Latex and the xfrac package, I am getting an error, I can save the figure in other formats, but not in PostScript
This is the code that I use..
import matplotlib
import matplotlib.pyplot as plt
# Use LaTeX for rendering
matplotlib.rcParams["text.usetex"] = True
# load the xfrac package
matplotlib.rcParams["text.latex.preamble"].append(r'\usepackage{xfrac}')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1],[1,0])
ax.text(.5, .5, r'$\sfrac{1}{2}$')
plt.savefig('111.ps')
This is the error that I get ( If I do not use xfrac package I do not get an error)
LaTeX was not able to process your file:
Here is the full report generated by LaTeX:
This is pdfTeX, Version 3.14159265-2.6-1.40.15 (TeX Live 2014) (preloaded format=latex)
restricted \write18 enabled.
entering extended mode
(/tmp/tmp0Nr4Ze.tex
LaTeX2e <2014/05/01>
Babel <3.9k> and hyphenation patterns for 79 languages loaded.
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/base/article.cls
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/base/size10.clo))
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/type1cm/type1cm.sty)
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/psnfss/helvet.sty
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/graphics/keyval.sty)
) (/home/users/MyName/Local/Latex/texmf-dist/tex/latex/psnfss/courier.sty
) (/home/users/MyName/Local/Latex/texmf-dist/tex/latex/base/textcomp.sty
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/base/ts1enc.def))
(/home/users/MyName/texmf/tex/latex/xfrac.sty
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/amsmath/amstext.sty
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/amsmath/amsgen.sty))
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/graphics/graphicx.st
y
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/graphics/graphics.st
y (/home/users/MyName/Local/Latex/texmf-dist/tex/latex/graphics/trig.sty)
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/latexconfig/graphics
.cfg)
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/graphics/dvips.def))
) (/home/users/MyName/texmf/tex/latex/l3keys2e.sty
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/l3kernel/expl3.sty
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/l3kernel/expl3-code.
tex
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/etex-pkg/etex.sty))
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/l3kernel/l3unicode-d
ata.def)
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/l3kernel/l3dvips.def
))) (/home/users/MyName/texmf/tex/latex/xparse.sty)
(/home/users/MyName/texmf/tex/latex/xtemplate.sty))
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/geometry/geometry.st
y
(/home/users/MyName/Local/Latex/texmf-dist/tex/generic/oberdiek/ifpdf.sty
)
(/home/users/MyName/Local/Latex/texmf-dist/tex/generic/oberdiek/ifvtex.st
y)
(/home/users/MyName/Local/Latex/texmf-dist/tex/generic/ifxetex/ifxetex.st
y)
Package geometry Warning: Over-specification in `h'-direction.
`width' (614.295pt) is ignored.
Package geometry Warning: Over-specification in `v'-direction.
`height' (794.96999pt) is ignored.
) (/home/users/MyName/Local/Latex/texmf-dist/tex/latex/psfrag/psfrag.sty)
! LaTeX Error: Option clash for package graphicx.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.13 \usepackage
{color}
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/graphics/color.sty
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/latexconfig/color.cf
g)
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/graphics/dvipsnam.de
f))
No file tmp0Nr4Ze.aux.
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/base/ts1cmr.fd)
(/home/users/MyName/Local/Latex/texmf-dist/tex/latex/psnfss/ot1pnc.fd)
*geometry* detected driver: dvips
<tmp0Nr4Ze.eps> [1] (./tmp0Nr4Ze.aux) )
(see the transcript file for additional information)
Output written on tmp0Nr4Ze.dvi (1 page, 3368 bytes).
Transcript written on tmp0Nr4Ze.log.
anyone has any idea how to solve this?
EDIT
I now found out that if I try to save it as pgf ( LaTeX PGF Figure)
I get this error
Error processing '\(\displaystyle \sfrac{\tau_{peel}}{\tau_{m}}\)'
LaTeX Output:
! Undefined control sequence.
<argument> ...}\selectfont \(\displaystyle \sfrac
{\tau _{peel}}{\tau _{m}}\)
<*> ...splaystyle \sfrac{\tau_{peel}}{\tau_{m}}\)}
No pages of output.
Transcript written on texput.log.
EDIT2:
I some times got this error
dvipng warning: No image output from inclusion of raw PostScript GPL Ghostscript 9.05: Unrecoverable error, exit code 1
So I updated Ghostscript and now I get this error :-)
dvipng warning: No image output from inclusion of raw PostScript GPL Ghostscript 9.14: Unrecoverable error, exit code 1
In this case in order to output ps — You need to pass dvips option to graphicx:
\usepackage[dvips]{graphicx}
The script should be:
import matplotlib
import matplotlib.pyplot as plt
# Use LaTeX for rendering
matplotlib.rcParams["text.usetex"] = True
# load the xfrac package
matplotlib.rcParams["text.latex.preamble"].append(r'\usepackage[dvips]{graphicx}\usepackage{xfrac}')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1],[1,0])
ax.text(.5, .5, r'$\sfrac{1}{2}$')
plt.savefig('111.ps')
Probably the graphicx is loaded by the matplotlib, and in order to output ps matplotlib uses dvips driver, and as so the option must be passed to the graphicx.
I think though it is easier to output pdf with Your original code and convert it to ps with ghostscript.