Context
I'm looking for a simple way to import properly typeset mathematics (with LaTeX) into blender. A solution for this has already been given. But that means getting out of blender, using multiple tools and then going back to blender and importing the whole thing.
Blender comes with Python and can import svg
I'd like to find an other way and blender has a set of powerful tools based on Python. I was thinking: can I make Python parse some TeX input and then generate a svg (virtual) file inside blender. That would solve the problem.
matplotlib "emulates" TeX
It is possible to install any Python library and use it inside blender. So this made me think of a possible "hack" of matplotlib.
mathtext is a module that provides a parser for strings with TeX-like syntax for mathematical expressions. svg is one of the available "backends".
Consider the following snippet.
import matplotlib.mathtext as mathtext
parser = mathtext.MathTextParser('svg')
t = parser.parse(r'$\int_{0}^{t} x^2 dx = \frac{t^3}{3}$')
t is a tuple that has all the information needed. But I can't find a way (in the backend api) to convert it to a (virtual) svg file.
Any ideas?
Thanks
Matplotlib needs a figure (and currently also a canvas) to actually be able to render anything. So in order to produce an svg file whose only content is a text (a mathtext formula) you still need a figure and a canvas and the text needs to actually reside inside the figure, which can be achieved by fig.text(..).
Then you can save the figure to svg via fig.savefig(..). Using the bbox_inches="tight" option ensures the figure to be clipped to the extent of the text. And setting the facecolor to a transparent color removes the figure's background patch.
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
fig = Figure(figsize=(5, 4), dpi=100)
canvas = FigureCanvasAgg(fig)
fig.text(.5, .5, r'$\int_{0}^{t} x^2 dx = \frac{t^3}{3}$', fontsize=40)
fig.savefig("output.svg", bbox_inches="tight", facecolor=(1,1,1,0))
Related
I got a super graph that I would like to export as an html file to be showed on an website but I don't know how to figure that. Have you got an idea ?
You can use mpld3. This is a great tutorial. The mpld3 library's main functionality is to take an existing matplotlib visualization and transform it into some HTML code that you can embed on your website.
Use fig_to_html file, which accepts a matplotlib figure object as its sole argument and returns HTML.
To use the fig_to_html method , simply add the following code to the end of our Python script:
html_str = mpld3.fig_to_html(fig)
Html_file= open("index.html","w")
Html_file.write(html_str)
Html_file.close()
basically the title is the question:
I would like to use lualatex for all the text handling in a matplotlib plot without using the pgf backend.
I need fontenc package and customized fonts to have identical fonts in plots and in my latex documents but do not want to use the pgf backend.
Is there a hidden option somewhere?
The context is the following: I have a mycommands.sty file where all my defind \newcommand for math are stored. I use some specific fonts for, e. g., \mathscr{p}, which is not possible (small letter) without the fontenc package.
Now I want to use these custom commands in different places (legend, labels, title, ...) in the plot and have them work and look exactly the same as in the document I write and compile with lualatex.
The only point why it is not possible is that matplotlib internally uses pdflatex for the compilation which gives me errors when using fontenc and therefore some of my commands do not work.
Thanks.
I am trying to scale my decision tree to fit notebook but it appears not to scale properly. I have to keep scrolling for a better view. Can I please have some help on how to fix this. Attach is a pic of how it looks like.
from graphviz import Source
from sklearn import tree
from IPython.display import SVG
graph = Source( tree.export_graphviz(dt_classifier, out_file=None, feature_names=X.columns))
SVG(graph.pipe(format='svg'))
Perhaps it's not relevant any more, since this question has been open for about six months now. However, I just stumbled into it, as apparently 83 other readers, and I just crafted my way around this. The easy way is to use the pydot package (pip install pydot), and then add the default size. I have also been using %matplotlib inline so that it displays nicely within the notebook but without using the svg module. With your example:
%matplotlib inline
from graphviz import Source
from sklearn import tree
import pydot
dot_data = tree.export_graphviz(dt_classifier, out_file=None, feature_names=X.columns))
pdot = pydot.graph_from_dot_data(dot_data)
# Access element [0] because graph_from_dot_data actually returns a list of DOT elements.
pdot[0].set_graph_defaults(size = "\"15,15\"")
graph = Source(pdot[0].to_string())
graph
I also added rotate=True to export_graphviz so that it displays in horizontal style, the root of the tree is directly visible, and is easier to follow. Of course, you can play around with size so as to reach something that is acceptable for you.
I'm trying to import a triangle mesh from file (e.g., .3ds, .dae). However, it seems that some of the faces (triangles) are being ignored. If I scale the model by 10x before importing, then the triangles are in tact. Is there a way to force sketchup to load all faces, even small ones?
Here's an example of loading a closed mesh (no boundaries) at its regular scale. SketchUp has ignored a few of the triangles, creating holes and dangling edges:
If I shrink the model, the problems are much worse:
But if I scale up the model enough, the problems go away:
Also, immediately after I import my cursor is set to "move mode", so the object is placed wherever my cursor randomly happens to be. Is there a way to import the model exactly into the current coordinate system without mouse interaction?
Yes, it's a known problem that Sketchup doesn't import very small edges/faces correctly. You can automate the import process of an upscaled model with this ruby script though:
model = Sketchup.active_model
# Import your dwg file, true if you want the summary screen
model.import 'C:\path\to\example.dwg', false
# Reset the selected tool
model.select_tool(nil)
# Get all imported faces
faces = model.entities.grep(Sketchup::Face)
# Create a new ComponentDefinition
definition = model.definitions.add "dwg"
# Add the points of every face to the definition
faces.each{|f| definition.entities.add_face f.vertices}
# Remove all entities
model.entities.clear!
# Create a new DefinitionInstance that is scaled by 0.5
transformation = Geom::Transformation.new(0.5)
instance = model.entities.add_instance definition, transformation
# Explode the component to work with the model
instance.explode
This adds the component to the origin and takes care of scaling the imported model back. If your model were a skp file, you could even load it directly into a ComponentDefinition, but that doesn't work for dwg files.
I’m writing a Python program that uses matplotlib. I’d like to use a font that isn’t included with matplotlib. (Well, I want to use Lucida Grande, which is included in OS X, but matplotlib can’t read the .dfont file directly so I need to distribute my own .ttf font.)
It seems like matplotlib only ever looks in one directory for fonts: mpl-data/fonts. It’s possible to tweak matplotlib’s configuration to change where the mpl-data directory is, but it doesn’t seem to be possible to specify more than one such directory in which fonts may be found. Is that accurate?
(It would be possible for me to put the font in my system’s global mpl-data directory, but it feels wrong for an application to muck around with a globally-used directory like that. And I sure as hell don’t want to include the entire mpl-data-plus-one-file with my application.)
One possibility is to expand on the response provided here which uses the matplotlib font manager module. Specifically, it looks like you can specify the absolute path to your font with the fname argument to matplotlib.font_manager.FontProperties (see the docs here: http://matplotlib.org/api/font_manager_api.html#matplotlib.font_manager.FontProperties)
Modifying the previous SO response (to a slightly simpler question) below, this is certainly worth a try if you can specify the absolute path to the ttf font file in your workflow. I've used a built-in MacOS font below (and that works), but maybe try substituting your particular absolute path & font to see if it works.
import matplotlib
matplotlib.use( "agg" ) #some backend sensitivity explained in previous SO response
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
fig, ax = plt.subplots()
#specify the absolute path to your font file:
absolute_path_to_ttf_file = '/opt/X11/share/fonts/TTF/VeraSe.ttf'
prop = fm.FontProperties(fname=absolute_path_to_ttf_file)
ax.set_title('Text in a cool font', fontproperties=prop, size=40)
plt.show()
plt.savefig('test.png')