Python matlplotlib add hyperlink to text - python

I've created a plot in Python using matplotlib. After annotating each line, I'd like to make the label a hyperlink (or alternatively, make the line itself a hyperlink). The text item has a property called 'url', but I've tried it and I can't figure out what, if anything, it does.
Is it possible to make text or line objects into hyperlinks?

This example shows how to set hyperlinks if you're outputting an SVG. Note that this only makes sense for SVG. If the plot is just an image, it's just an image, and images can't have hyperlinks in them.
If you want to be able to click on the object in the interactive plotting window and have that act like a hyperlink, you could create an event handler to handle the "pick" event, and have that open a browser or whatever. See this example for how to do pick events. Matplotlib plots aren't web pages or even really documents, they're just windows with graphics displayed in them, so they don't support hyperlinks as such; using a pick event you can emulate a hyperlink by opening a web browser when an object is clicked.
Edit: You are right, it doesn't work. It seems that the URL property is only read and used for certain types of objects. Googling, I see some old matplotlib mailing list discussion of it, where it seems the idea was to gradually add URL support to different artist types, but I guess they never got around to it. I would suggest you raise a bug about this on the matplotlib bug tracker.
In the meantime, there is a way to do it, but it is somewhat roundabout. The URL is drawn for PathCollection objects, so you could make a Path out of your text, then make a PathCollection out of that path, and then add that PathCollection to your plot. Here's an example:
pyplot.scatter([1, 2, 3], [4, 5, 6])
t = mpl.text.TextPath((2, 4), 'This is text', size=0.1)
pc = mpl.collections.PathCollection([t])
pc.set_urls(['http://www.google.com'])
ax = pyplot.gca()
ax.add_collection(pc)
pyplot.draw()
f = pyplot.gcf()
f.canvas.print_figure('fig.svg')
Note that you must use set_urls and not set_url. This method produces an SVG with clickable text, but it has some drawbacks. Most notably, it seems you have to set the text size manually in data coordinates, so it may take some fiddling to find a text size that isn't too ridiculously huge or tiny relative to the magnitude of your plotted data.

Adding a hyperlink makes sense when e.g. using an SVG file.
The url property works in newer matplotlib versions:
text = plt.annotate("Link", xy=(2,5), xytext=(2.2,5.5),
url='http://matplotlib.org',
bbox=dict(color='w', alpha=1e-6, url='http://matplotlib.org'))
For example, in a Jupyter notebook, which runs in a browser anyways, one could display an SVG with hyperlinks like this:
import matplotlib.pyplot as plt
from IPython.display import set_matplotlib_formats
set_matplotlib_formats("svg")
fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [4, 5, 6])
text = ax.annotate("Link", xy=(2,5), xytext=(2.2,5.5),
url='http://matplotlib.org',
bbox=dict(color='w', alpha=1e-6, url='http://matplotlib.org'))
In the figure produced this way you may click on the link and be directed to matplotlib.org.

This is possible with pgf backend:
#!/usr/bin/env python3
import matplotlib
matplotlib.use("pgf")
pgf_with_custom_preamble = {
"text.usetex": True,
"pgf.preamble": [
r"\usepackage{hyperref}"
]
}
matplotlib.rcParams.update(pgf_with_custom_preamble)
from matplotlib import pyplot as plt
x = range(5)
y = range(5)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, "r-", label=r"Hyperlink: \url{http://google.com}")
ax.legend()
fig.savefig("mwe.pdf")

Related

Image not updating in python plot during animation

The Problem:
I'm trying to simulate a live video by cycling through a series of still images I have saved in a directory, but when I add the animation and update functions my plot is displayed empty.
Background on why I'm doing this:
I believe its important for me to do it this way rather than a complete change of approach, say turning the images into a video first then displaying that, because what I really want to test is the image analysis I will be adding and then overlaying on each frame. The final application will be receiving frames one by one from a camera and will need to do some processing, display the image + annotations + output the data as .csv etc... I'm simulating this for now because I do not have any of the hardware to generate the images and will not have it for several months during which time I need to get the image processing set up, but I do have access to some sets of stills that are approximately what will be produced. In case its relevant my simulation images are 1680x1220 and are 1.88 Mb TIFFs, though I could covert and compress them if needed, and in the final form the resolution will be a bit higher and probably the image format could be adjusted if needed.
What I have tried:
I followed an example to list all files in a folder, and an example
to update a plot. However, the plot displays blank when I run the
code.
I added a line to print the current file name, and I can see this
cycling as expected.
I also made sure the images will display in the plot if I just create
a plot and add one image, and they do. But, when combined with the
animation function the plot is blank and I'm not sure what I've done
wrong/failed to include.
I also tried adding a plt.pause() in the update, but again this
didn't work.
I increased the interval up to 2000 to give it more time, but that didn't work. I believe 2000 is extreme, I'm expecting it should work with more like 20-30fps. Going to 0.5fps tells me the code is wrong or incomplete, rather than it just being a question of needing time to read the image file.
I appreciate no one else has my images, but they are nothing special. I'm using 60 images but I guess it could be tested with any 2 random images and setting range(60) to range(2) instead?
The example I copied originally demonstrated the animation function by making a random array, and if I do that it will show a plot that updates with random squares as expected.
Replacing:
A = np.random.randn(10,10)
im.set_array(A)
...with my image instead...
im = cv2.imread(files[i],0)
...and the plot remains empty/blank. I get a window shown called "Figure1" (like when using the random array), but unlike with the array there is nothing in this window.
Full code:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import os
import cv2
def update(i):
im = cv2.imread(files[i],0)
print(files[i])
#plt.pause(0.1)
return im
path = 'C:\\Test Images\\'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.TIFF' in file:
files.append(os.path.join(r, file))
ani = FuncAnimation(plt.gcf(), update, frames=range(60), interval=50, blit=False)
plt.show()
I'm a python and a programming novice so have relied on adjusting examples others have given online but I have only a simplistic understanding of how they are working and end up with a lot of trial and error on the syntax. I just can't figure out anything to make this one work though.
Cheers for any help!
The main reason nothing is showing up is because you never add the images to the plot. I've provided some code below to do what you want, be sure to look up anything you are curious about or don't understand!
import glob
import os
from matplotlib import animation
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
IMG_DIRPATH = 'C:\\Test Images\\' # the folder with your images (be careful about
# putting spaces in directory names!)
IMG_EXT = '.TIFF' # the file extension of your images
# Create a figure, and set to the desired size.
fig = plt.figure(figsize=[5, 5])
# Create axes for the current figure so that images can be sized appropriately.
# Passing in [0, 0, 1, 1] makes the axes fill the whole figure.
# frame_on=False means we won't have a bounding box, and setting xticks=[] and
# yticks=[] means that we won't have pesky tick marks along our image.
ax_props = {'frame_on': False, 'xticks': [], 'yticks': []}
ax = plt.axes([0, 0, 1, 1], **ax_props)
# Get all image filenames.
img_filepaths = glob.glob(os.path.join(IMG_DIRPATH, '*' + IMG_EXT))
def update_image(img_filepath):
# Remove all existing images on the axes, and restore our settings.
ax.clear()
ax.update(ax_props)
# Read the current image.
img = mpimg.imread(img_filepath)
# Add the current image to the plot axes.
ax.imshow(img)
anim = animation.FuncAnimation(fig, update_image, frames=img_filepaths, interval=250)
plt.show()

Latex font in matplotlib - Script-r

In matplotlib, one can easily use latex script to label axes, or write legends or any other text. But is there a way to use new fonts such as 'script-r' in matplotlib? In the following code, I am labelling the axes using latex fonts.
import numpy as np
import matplotlib.pyplot as plt
tmax=10
h=0.01
number_of_realizations=6
for n in range(number_of_realizations):
xpos1=0
xvel1=0
xlist=[]
tlist=[]
t=0
while t<tmax:
xlist.append(xpos1)
tlist.append(t)
xvel1=np.random.normal(loc=0.0, scale=1.0, size=None)
xpos2=xpos1+(h**0.5)*xvel1 # update position at time t
xpos1=xpos2
t=t+h
plt.plot(tlist, xlist)
plt.xlabel(r'$ t$', fontsize=50)
plt.ylabel(r'$r$', fontsize=50)
plt.title('Brownian motion', fontsize=20)
plt.show()
It produces the following figure
But I want 'script-r' in place of normal 'r'.
In latex one has to add the following lines in preamble to render 'script-r'
\DeclareFontFamily{T1}{calligra}{}
\DeclareFontShape{T1}{calligra}{m}{n}{<->s*[2.2]callig15}{}
\DeclareRobustCommand{\sr}{%
\mspace{-2mu}%
\text{\usefont{T1}{calligra}{m}{n}r\/}%
\mspace{2mu}%
}
I don't understand how to do this in matplotlib. Any help is appreciated.
Matplotlib uses it's own hand-rolled (pure Python) implementation of TeX to do all of the math text stuff, so you absolutely cannot assume that what works in standard LaTeX will work with Matplotlib. That being said, here's how you do it:
Install the calligra font so that Matplotlib can see it, then rebuild the font cache.
Lots of other threads deal with how to do this, I'm not going to go into detail, but here's some reference:
Use a font installed in a random spot on your filesystem.
How to install a new font into the Matplotlib managed font cache.
List all fonts currently known to your install of Matplotlib.
Replace one of Matplotlib's TeX font families with your font of choice.
Here's a function I wrote a while ago that reliably does that:
import matplotlib
def setMathtextFont(fontName='Helvetica', texFontFamilies=None):
texFontFamilies = ['it','rm','tt','bf','cal','sf'] if texFontFamilies is None else texFontFamilies
matplotlib.rcParams.update({'mathtext.fontset': 'custom'})
for texFontFamily in texFontFamilies:
matplotlib.rcParams.update({('mathtext.%s' % texFontFamily): fontName})
For you, a good way to use the function would be to replace the font used by \mathcal with calligra:
setMathtextFont('calligra', ['cal'])
Label your plots, for example, r'$\mathcal{foo}$', and the contents of the \math<whatever> macro should show up in the desired font.
Here's how you'd change your label-making code:
plt.ylabel(r'$\mathcal{r}$', fontsize=50)
and that should do it.

Plotly opens prompt screen after drawing plot

I use the following code to draw a heatmap in plotly:
import plotly.offline as plotly
import plotly.graph_objs as graph_objs
x = []
# fill x with stuff
path = os.path.join(self.get_current_job_directory(), track + '.html')
trace = graph_objs.Heatmap(z = x)
data = [trace]
plotly.plot(data, filename = path)
But I get a prompt screen like this. I need to generate hundreds of such plots on a remote server and its not practical to just dismiss them.
How to get rid of this?
Using the filename argument tells Plotly what filename to use for the HTML file it generates to contain the plot. That file is then viewed in the system's default HTML viewer, which in this case appears to be Lynx. Of course that's rather useless as the point is to view the plot, and Lynx is a text-only Web browser!
To avoid opening the plot, add auto_open=False to your plot() call:
plotly.plot(data, filename=path, auto_open=False)

How can I automatically combine matplotlib graphs with Adobe Illustrator vector illustrations?

I'm currently writing a scientific paper and am generating most of the figures using matplotlib. I have a pipeline set up using a makefile that regenerates all of my plots whenever I update the data. My problem is that the figures are made up multiple panels, and some of those panels should contain vector illustrations which I've created using Adobe Illustrator. How can I automatically combine the graphs with the illustrations when I update my raw data? I could save the vector illustrations in a raster format and then display them using matplotlib's imshow function, but I want the output to be a vector to ensure the best possible print quality.
After some more extensive googling I found this old message on the matplotlib mailing list:
The thread suggests using the python library PyX, which works well for me.
I can save both the illustrator diagrams and the matplotlib plots as .eps files, and then combine them together like this:
import pyx
c = pyx.canvas.canvas()
c.insert(pyx.epsfile.epsfile(0, 0, "1.eps", align="tl"))
c.insert(pyx.epsfile.epsfile(0,0,"2.eps", align="tr"))
c.writeEPSfile("combined.eps")
I found this example in the svgutils documentation which outlines how to combine matplotlib-generated SVGs into a single plot.
Here's the example from that page:
import svgutils.transform as sg
import sys
#create new SVG figure
fig = sg.SVGFigure("16cm", "6.5cm")
# load matpotlib-generated figures
fig1 = sg.fromfile('sigmoid_fit.svg')
fig2 = sg.fromfile('anscombe.svg')
# get the plot objects
plot1 = fig1.getroot()
plot2 = fig2.getroot()
plot2.moveto(280, 0, scale=0.5)
# add text labels
txt1 = sg.TextElement(25,20, "A", size=12, weight="bold")
txt2 = sg.TextElement(305,20, "B", size=12, weight="bold")
# append plots and labels to figure
fig.append([plot1, plot2])
fig.append([txt1, txt2])
# save generated SVG files
fig.save("fig_final.svg")

How do I print a PDF file to a printer in landscape from Python?

I'm using Mac OSX but I need a platform independent method to print a pdf file.
I created a graph in Matplotlib and want to print it to my printer.
I can set the orientation of the canvas to fit a portrait layout with:
fig.set_size_inches( 8.27,11.69) # set the figure size in inches
but using:
fig.set_size_inches( 11.69, 8.27)
prints a cropped portrait oriented figure
I found this on another post here:
import subprocess
import shlex
printfile='test.pdf'
fig.savefig(printfile)
proc=subprocess.Popen(shlex.split('lpr {f}'.format(f=printfile)))
Can anyone help me with the format of the code to set the print orientation to landscape?
I have seen lpr -o landscape, but do not have enough experience with it to know if it works for all printers.
Rather than changing orientation while printing, you can do it when generating the image (if it fits with your workflow). The matplotlib savefig command allows you to specify saving in landscape orientation, but currently only for postscript. That is not a problem, however, since we can easily convert the postscript file to PDF format. Below is an example.
In Python:
from pylab import *
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plot(x, y)
xlabel('x')
ylabel('y')
savefig('img.eps', orientation='landscape')
I left out the canvas size for convenience and brevity.
Now we have a file named img.eps. In the shell do the following.
epstopdf img.eps
Here is what the resulting img.pdf file looks like:
One downside to keep in mind with this approach is that postscript does not like transparency, so if you want transparency this is not the approach for you. To see what I mean take the matplotlib patch_collection.py example. Replace the pylab.show() on the last line with pylab.savefig('patch.pdf'), run it, and then look at the resulting PDF file. It will look like the image in the example. If, however, you do pylab.savefig('patch.eps'), you will see that the objects are all opaque.

Categories

Resources