Numbered reference to figures in Sphinx - python-sphinx

Using sphinx 1.3.6, I cannot find a way to make numbered references to figures.
According to answers and comments here: Referencing figures with numbers in Sphinx and reStructuredText,
numref is built into Sphinx.
But this simply does not work:
.. _mylabel
.. figure:: img/fig.jpg
this is the caption
When I use :numref:`Figure %s <mylabel>` in the text, the result is literally Figure %s as if numref was actually not implemented at all.
Do I need something to put in conf.py or in the latex preamble?

I realise this is an old post, however I thought I'd share what helped me in this case.
The following code will add a numbered link to your image with a numbered title. For example the link Fig. 1 will link to the image with the title: Fig. 1 System Process Flow
documentation.rst File:
This is some boring documentation text which refers to the illustration in :numref:`my-image`.
.. figure:: images/process_flow.png
:name: my-image
:align: center
:width: 100%
System Process Flow
conf.py File:
Add this line to your conf.py file:
numfig = True
Your Sphinx doc will now have a link to your numbered figure.

Additionally, page.rst has to be included in some 'toctree'.
Else it will throw errors as follows:
WARNING: no number is assigned for figure:

Related

Repeat or reference a figure in another rst file

I have two files named a.rst and b.rst, both of which contain a good deal of text. In a.rst, I define a figure:
.. figure:: ../images/some-image.png
:scale: 70%
:align: center
:alt: Some Text
Some Caption
I would like to have the same image and caption in b.rst with the same figure number, But repeating the above code gives me a new figure.
As a compromise, I can refer to this image in b.rst using the :numref: directive, but that does not resolve to the figure. It only displays the name as a piece of code.
I understand that these are two question, but I think they are sufficiently related. How can I repeat or reference a figure defined in a rst file in another file.
Edit to elaborate on the expected output:
I want the resulting files to have the following content:
a.html:
Fig. 1 + caption
Fig. 2 + caption
Fig. 3 + caption
b.html:
Fig. 4 + caption
Fig. 2 + caption
Fig. 5 + caption
Effectively, this would add the figure to b.rst not as a separate entity, but merely as a mirror of what was in a.rst. This is similar to what was discussed here.
Assuming you want to repeat the exact same content in two different files, put that content into a separate file, then include that file wherever you want it to appear.
includeme.rst
Note document root relative path.
.. figure:: /images/some-image.png
:scale: 70%
:align: center
:alt: Some Text
Some Caption
a.rst and b.rst
Below this paragraph should appear an image.
..include:: /includeme.rst
EDIT
To remove the figure number, set numfig to False. This will avoid the incongruent figure numbering, but won't solve it. I think that's the best you can achieve, as Sphinx automatically numbers figures (and other objects) otherwise.

Broken Image Links in Markdown

I am working on the .md file in the following location:
https://github.com/markroche92/SDND-Traffic-Sign-Classification/blob/master/writeup_template.md
None of my linked images are appearing when I view the .md file in Github. I have used the following markdown code to attempt to link the images:
---
**Build a Traffic Sign Recognition Project**
[//]: # (Image References)
[image1]: ./histogram_input_data.png "Input_Data"
[image2]: ./Label26.png "Label_26"
[image3]: ./Label36.png "Label_36"
[image4]: ./Label41.png "Label_41"
[image5]: ./channels.png "Channels"
[image6]: ./nn_results.png "NN_Results"
[image7]: ./GermanRoadSigns/x32/132.jpg "Img_1"
[image8]: ./GermanRoadSigns/x32/232.jpg "Img_2"
[image9]: ./GermanRoadSigns/x32/332.jpg "Img_3"
[image10]: ./GermanRoadSigns/x32/432.jpg "Img_4"
[image11]: ./GermanRoadSigns/x32/532.jpg "Img_5"
[image12]: ./int_ims.png "Performance"
[image13]: ./top_five_predictions.png "Top_Five_Predictions"
[image14]: ./structure.jpg "Network_structure"
---
...
The following histogram shows the distribution of training, validation and
test set images per label:
![alt text][image1]
An example image was visualised for each label. Three are displayed below:
![alt text][image2]
![alt text][image3]
![alt text][image4]
Each image has three channels (red, green, blue). The three channels are
visualized below for an example image:
![alt text][image5]
However, none of the images seem to be appearing when .md is viewed on Github. Can anyone show me where I am going wrong here?
In the actual .md file you are not using relative URLs like in your supposed quote, but absolute ones like this:
https://github.com/markroche92/SDND-Traffic-Sign-Classification/blob/master/structure.JPG
This won’t work because it is actually a standard GitHub file page, not the image itself. To link to the image, remove /blob from the path and change the domain to rawgit.com – or actually use relative URLs with or without leading ./, but make sure to get the letter case right.
https://rawgit.com/markroche92/SDND-Traffic-Sign-Classification/master/structure.JPG
structure.JPG
I also had this issue on some of my images, but not others. It ended up being how I capitalized my image names in my markdown file. For example:
Image name on my computer:
oneGreatImage.png
Image name in my Markdown file:
onegreatImage.png
When I capitalized the G again and pushed the changes it loaded just fine.
It appears that GitHub is VERY picky about matching the filenames on the images so double check that.

How to create floating figures in reStructuredText / Sphinx?

I want to have a figure with text wrapped around it.
This is what I'm saying:
Installation of Optional Accessories
====================================
.. warning:: Never plug in or unplug a Hand Robot or a Grasp Sensor while the robot is turned on, as the system will not function properly and damage to the robot could occur.
Installing a Hand Robot
-----------------------
.. _`fig-attach-hand-robot`:
.. figure:: attach-hand-robot.*
:scale: 40%
:align: right
Attach Hand Robot
Make sure the robot is turned off as described in the section :ref:`turn-off-robot`.
Take the hand robot out of the grounded bin that sits on top of the electrical panel (if you have an adjustable height table) or sits on top of the rear table (if you have a fixed height table). Make sure not to touch the pins on the electrical wiring while doing so. Insert the conical protrusion of the hand robot into the conical receptacle (see :ref:`fig-attach-hand-robot`). Once the hand robot is supported by the InMotion Arm Robot, make sure the two knobs below the Hand Robot have engaged and sprung in. If they have not, twist them until they do as shown (see :ref:`fig-knobs-in`).
and this screenshot of PDF output is what I'm getting.
Why is the figure caption centered, rather than under the image?
Why isn't the body text ("Make sure ..." and "Take the ...") on the LEFT of the image, rather than underneath it? I want the figure to float right and have the text on its left.
I have found that figures float to the side with :figwidth: and :align: specified. (Using the readthedocs theme.)
.. figure:: images/myimage.jpg
:figwidth: 40%
:align: right
https://docutils.sourceforge.io/docs/ref/rst/directives.html#figure
So, I did some research into reStructuredText and it seems what you want is not actually possible.
The documentation for the figure and the image directives never mention the ability to wrap text around the object.
This might be a feature request to provide to the Sphinx developers although I suspect they'll reject it because it isn't explicitly mentioned in the rst specification.
I was hoping the bounty would garner this some attention but I suspect is hasn't.
Though it is too late but maybe the answer would help future people.
You can use the sidebar directive to put the image.
.. sidebar:: mandatory_title. Use can use image caption here
.. Figure:: 1.png
In order to deal with images as they were part of the text you may actually use substitutions.
Here an extract from the documentation that can be helpful:
The |biohazard| symbol must be used on containers used to
dispose of medical waste.
.. |biohazard| image:: biohazard.png
I hope this helps
If anyone else runs into this problem then this bit of code might be a help. I decided that I didn't want to hack the actual sphinx code so I made a very short python script applied to the generated _build/latex/pi3d_book.tex to convert the \includegraphics that had \hfill before or after into wrapped images. There will be lots of things that stop this working such as putting images inside lists or scaling images. The sphinx directives in my rst are like
.. image:: perspective.png
:align: right
You obviously have to change the file names and paths to suit your setup. From my spinx project I run
$ make latexpdf
$ python wrapfix.py # or whatever you call this file
program listing of wrapfix.py
import subprocess
with open("_build/latex/pi3d_book.tex", "r") as f:
tx = f.read().splitlines()
txnew = []
flg1 = True
for line in tx:
if line == "" and flg1:
txnew += ["\\usepackage{wrapfig}",""]
flg1 = False # just do this once before first blank line
elif "includegraphics{" in line and "hfill" in line:
fname = line.split("{")[2].split("}")[0]
if line.startswith("{\\hfill"): # i.e. right justify
fl_type = "R"
else:
fl_type = "L"
txnew += ["\\begin{wrapfigure}{" + fl_type + "}{0.35\\textwidth}",
"\\includegraphics[width = 0.3\\textwidth]{" + fname + "}",
"\\end{wrapfigure}"]
else:
txnew += [line]
txnew = "\n".join(txnew)
with open("_build/latex/pi3d_book.tex", "w") as fo:
fo.write(txnew)
subprocess.Popen(["pdflatex", "pi3d_book"], cwd="/home/jill/pi3d_book/_build/latex")

Linking to figures in Sphinx

I have some images in my documentation created as a set of reST files in Sphinx. I prefer to keep them pretty small, and I want the user to click on them to get the larger image. The smaller image is not for file size reasons but for presentation reasons. I do not find a syntactic way to combine the tags image: or figure: with ref: or link:.
.. image:: _static/my_image_small.png
and I have a bigger version in the same folder: my_image_large.png.
If you come up with a solution, should the larger image just be a file with an explicit link to it or do I create a reST file with an additional image: tag? An alternative could be to play with the image sizes in the reST file, but then I still do not know how to create the link from the small image to the large image. Is there a way to bypass the Sphinx generator and just give the HTML that I want?
There are two ways you can do it.
The first is to just insert a bit of "raw" HTML:
.. raw:: html
<a href=....><img src=....
The second is to make the image clickable. That way you can link it to a bigger image:
.. image:: _static/my_image_small.png
:target: _static/my_image_large.png
There are more options you can give, btw. See the full list in the restructured text documentation.

Thumbnail-like behavior using target attribute of image directive

I use Sphinx to generate some docs. I have a reStructuredText document and I'd like to put an image into it. The case is that the image should be clickable so that after a user clicks the image then they should be shown this image in full size. I use the image directive and its target option like this:
.. image:: /images/some_image.png
:alt: Image descripion
:align: center
:target: `big_some_image`_
.. _big_some_image: /images/some_image.png
The problem is that in the rendered page I get:
<img src="../../../_images/some_image.png">
So there is correct src from the image directive but an incorrect href attribute from the hyperlink.
Questions:
is there any way to generate links in the way that image directive does it? I mean relative to the document.
is there any other (built in) way to have "thumbnail-> click -> big image" behaviour?
Simply use the scale option:
.. image:: large_image.png
:scale: 20%
When the scaled image is clicked on, the full image loads in its own window. So this doesn't increase the image size on the page, but that would be messy anyway.
When you use the image directive from within Sphinx, Sphinx does some special handling to find the image file and copy it into your project (like your _images directory), and then renders the HTML to point to that place.
But the target option just takes a URL as a parameter. It knows nothing about your Sphinx project, or how your images are laid out, and does not attempt to guess.
If you want to have it point to a larger version of the same file, you will likely need to do some manual steps (like maybe copying the file to a specific location), or maybe provide a relative URL to the large file, rather than the absolute URL you have in your example.
If you want to go a completely different way, you could also try overriding and modifying the HTML templates for your project to add some JavaScript to get the click-to-larger-image effect you want.
Looks like there is a Sphinx extension that does this now, and quite nicely at that, sphinxcontrib-fancybox 0.3.2. Install with pip, add it to your extensions in conf.py, and use the fancybox directive:
.. fancybox:: images/image.png
Relative links seem to work. For the Mapserver docs setup, if an image is placed in the images directory, a relative link like in the following code works in my local build. Here is an example using figure (the underscore ("_") before "images" in the target link is necessary):
.. figure:: ../../images/carto-elements.png
:height: 400
:width: 600
:align: center
:target: ../../_images/symcon-overlay.png

Resources