Matplotlib navigation toolbar is invisible - python-2.7

When I plot an image, my Navigation toolbar (zoom-in, forward, back...) is invisible. I helped myself with this link: disable matplotlib toolbar. I have first tried:
import matplotlib as mpl
mpl.rcParams['toolbar'] = 'toolbar2'
And also checked if in the file itself is set as 'None' but it is not.
Did I perhaps forget to install some packages? Even though I don't get any errors.
Is there alternative way to zoom-in and see the coordinates of cursor, because that is all I need.
Edit 1
This is the code which I am using. I copied just the part, where I use plot.
#___plotting part___
import matplotlib as mpl
mpl.rcParams['toolbar'] = 'toolbar2'
import matplotlib.pyplot as plt
plt.ion()
fig, ax = plt.subplots(figsize=(20, 10))
ax.set_title(plot_titel, loc='center', fontname=font_name, fontsize=16, color='black')
ax.set_xlabel('Column number', fontname=font_name, fontsize=16, color='black')
ax.set_ylabel('Mean of raw backscatter', fontname=font_name, fontsize=16, color='black')
ax.plot(range(len(param_image)), param_image, c='black', marker='o')
ax.plot(idx1[0], param_image[idx1], c='red', mec='red', marker='o', linestyle='')
ax.plot(idx2, param_image[idx2], c='blue', mec='blue', marker='o', linestyle='')
ax.grid()
fig.tight_layout()
plt.show()

I had the same problem before. uninstall it and then install it again (try to use Anaconda or miniconda distribution to install). for sure after that it will work.
do not mess with matplotlibrc

Related

Displaying PNG in matplotlib.pyplot framework in python 2.7

I am pulling PNG images from Jupyter Notebooks and manage to display with IPython.display.Image but not with matplotib.pyplot.plt. What am I missing? I use python 2.7.
I am using the following algorithm:
To open the notebook JSON content I do:
import nbformat
notebook_ = nbformat.read(file_notebook, 4)
After retrieving the relevant cell information I pull the png information from it using:
def cell_to_image(cell, out_value_item_number=1):
if "execution_count" in cell.keys(): # i.e version >=4
return cell["outputs"][out_value_item_number]['data']['image/png']
elif "prompt_number" in cell.keys(): # i.e version < 4
return cell["outputs"][out_value_item_number]['png']
return None
cell_image = cell_to_image(cell)
The first few characters of cell_image (which is unicode) looks like:
iVBORw0KGgoAAAANSUhEUgAAA64AAAFMCAYAAADLFeHSAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\n
AAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xd8jef/x/HXyTjZiYQkCGrU3ruR0tr9oq2qGtGo0dbe
\nm5pVlJpFUSMoVb6UoEZ/lCpatWuPUiNEEiMDmef3R75OexonJKUO3s/HI4/mXPd1X/d1f+LRR965
\n7/u6DSaTyYSIiIiIiIiIjbJ70hMQERERERERyYiCq4iIiIiIiNg0BVcRERERERGxaQquIiIiIiIi
\nYtMUXEVERERERMSmKbiKiIiIiIiITVNwFRGRxyIkJIRixYqxfv36+24/e/YsxYoVo3jx4v/yzGxb
\naGgoderUIS4uDoBdu3bRsmVLKlasyCuvvMKgQYOIjo622CcsLIyGDRtSunRp6tSpw8KFC62OW7p0
\naRo2bJju53Lnzh1GjRrFyy+/TNmyZWnRogW//fbbQ835q6++olGjRpQvX5769eszc+ZMkpOTzdtT
\nU1OZNGkSNWrUoHTp0jRp0oTdu3enGyc2NpZOn
I can easily plot in my Jupityer notebook using
from IPython.display import Image
Image(cell_image)
And now to my question:
How can I manipulate cell_image to be plt.subplot friendly?
(Assuming import matplotlib.pyplot as plt).
I realise that plt.imshow wouldn't work because this would require an array, which is not my case (which is a string, as far as I understand).
If you have your image string representation in a variable string_rep, the following code should work.
from io import BytesIO
import matplotlib.image as mpimage
import matplotlib.pyplot as plt
with BytesIO(string_rep.decode('base64')) as byte_rep:
image = mpimage.imread(byte_rep)
plt.imshow(image)

Jupyter/ipython notebook : how to prevent plot redraw using interactive widget

I am struggling to have construct an interactive tool in jupyter notebook. Based on the discussion here : IPython Notebook widgets for Matplotlib interactivity, I've build the following example:
%matplotlib notebook
import matplotlib.pyplot as plt
from ipywidgets import Select,interactive,Dropdown
from IPython.display import display
fig,ax = plt.subplots()
ax.plot(range(5))
vline = ax.axvline(1, color='k')
hline = ax.axhline(0.5, color='k')
def set_cursor(x, y):
vline.set_xdata((x, x))
hline.set_ydata((y, y))
ax.figure.canvas.draw_idle()
interactive(set_cursor, x=ax.get_xlim(), y=ax.get_ylim())
It works pretty well except that that the last line (interactive...) has to be run in a different cell.
If I want to launch everything in the same cell (or from the same object if use a Class approach, which is what I want at the end), I have to use the following code:
%matplotlib notebook
import matplotlib.pyplot as plt
from ipywidgets import Select,interactive,Dropdown
from IPython.display import display
fig,ax = plt.subplots()
ax.plot(range(5))
vline = ax.axvline(1, color='k')
hline = ax.axhline(0.5, color='k')
def set_cursor(x, y):
vline.set_xdata((x, x))
hline.set_ydata((y, y))
ax.figure.canvas.draw_idle()
display(fig)
tool = interactive(set_cursor, x=ax.get_xlim(), y=ax.get_ylim())
display(tool)
But in this case, the complete figure is redraw each time a new value is selected in a widget
Is there any possibility to get everything launch smoothly from the same cell ?
Any idea is more than welcome !

PyQt4 and Qwt Error when opening

i´m trying to do a simple plot, using PyQt4 and Qwt5. When i start the app, it shows as i expected, but i can´t do anything, such as click or zoom for example. And if i minimize it, the plot disappears.
This is my code:
import sys
from PyQt4 import Qt
import numpy as np
import PyQt4.Qwt5.iqt
from PyQt4.Qwt5.qplt
class SimpleData(QwtPlot):
def __init__(self):
QwtPlot.__init__(self)
x = np.arange(-2*np.pi, 2*np.pi, 0.01)
p = IPlot(Curve(x, np.cos(x), Pen(Magenta,2), "cos(x)"),
Curve(x, np.exp(x), Pen(Red), "exp(x)", Y2),
Axis(Right, Log),"Ejemplo de PyQt con PyQwt")
x = x[0: -1: 10]
p.plot(Curve(x, np.cos(x-np.pi/4), Symbol(Circle, Yellow), "circle"),
Curve(x, np.cos(x+np.pi/4), Pen(Blue), Symbol(Square, Cyan), "Square"))
app = QApplication(sys.argv)
app.exec_()
The indentation is correct, maybe i made a mistake writting it here, but it´s ok.
Another thing, when i close the app, i get this error:
QObject::killTimers: timers cannot be stopped from another thread
[Finished in 2.6s with exit code -1073741510]
Thank you for your time and answers. I hope you can help me.

How to resolve UserWarning: findfont: Could not match :family=Bitstream Vera Sans

Following this example:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
for i, label in enumerate(('A', 'B', 'C', 'D')):
ax = fig.add_subplot(2,2,i+1)
ax.text(0.05, 0.95, label, transform=ax.transAxes,
fontsize=16, fontweight='bold', va='top')
plt.show()
I get this output:
Why are my labels normal weight, while the documentation shows this should create bold letters A, B, C, D?
I also get this warning:
Warning (from warnings module):
File "C:\Python27\lib\site-packages\matplotlib\font_manager.py", line 1228
UserWarning)
UserWarning: findfont: Could not match :family=Bitstream Vera Sans:style=italic:variant=normal:weight=bold:stretch=normal:size=x-small. Returning C:\Python27\lib\site-packages\matplotlib\mpl-data\fonts\ttf\Vera.ttf
OP Resolution
From a deleted answer posted by the OP on Sep 15, 2013
Ok, it was a problem with the installation of matplotlib
Try using weight instead of fontweight.
Maybe try using this -
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.labelweight'] = 'bold'
Do this at a global level in your program.
The example from your question works on my machine. Hence you definately have a library problem. Have you considered using latex to make bold text? Here an example
Code
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 1)
ax0, ax1, ax2 = axs
ax0.text(0.05, 0.95, 'example from question',
transform=ax0.transAxes, fontsize=16, fontweight='bold', va='top')
ax1.text(0.05, 0.8, 'you can try \\textbf{this} using \\LaTeX', usetex=True,
transform=ax1.transAxes, fontsize=16, va='top')
ax2.text(0.05, 0.95,
'or $\\bf{this}$ (latex math mode with things like '
'$x_\mathrm{test}^2$)',
transform=ax2.transAxes, fontsize=10, va='top')
plt.show()
Not sure if you're still having the issue. I tried your code in Anaconda/Spyder, Python 2.7. The plots appear with Bold labels (A,B,C,D). I agree the issue is probably with the library. Try replacing / updating font_manager.py or confirming font files are present:
Lib\site-packages\matplotlib\mpl-data\fonts\ttf\
I had the same problem and spent quite a few hours today on that. Here`s the solution that helped me:
import matplotlib
matplotlib.font_manager._rebuild()
With this, the font_manager could be upgraded easily.

Simple matplotlib Annotating example not working in Python 2.7

Code
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
ax.set_ylim(-2,2)
plt.show()
from http://matplotlib.org/1.2.0/users/annotations_intro.html
return
TypeError: 'dict' object is not callable
I manged to fixed it with
xxx={'facecolor':'black', 'shrink':0.05}
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=xxx,
)
Is this the best way ?
Also what caused this problem ? ( I know that this started with Python 2.7)
So if somebody know more, please share.
Since the code looks fine and runs ok on my machine, it seems that you may have a variable named "dict" (see this answer for reference). A couple of ideas on how to check:
use Pylint.
if you suspect one specific builtin, try checking it's type (type(dict)), or look at the properties/functions it has (dir(dict)).
open a fresh notebook and try again, if you only observe the problem in interactive session.
try alternate syntax to initialise the dictionary
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops={'facecolor':'black', 'shrink':0.05})
try explicitly instancing a variable of this type, using the alternate syntax (as you did already).