Update figure text in matplotlib figure in python - python-2.7

How to update figure text in matplotlib figure in python 2.7?
t = figtext(.78,.92, "Combined- Sensors ", horizontalalignment = 'center',fontsize=15,color= 'm')
I have tried using t.remove() but I am getting an error:
traceback (most recent call last):
File "C:\Python27\combined.py", line 245, in <module>
t.remove()
File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 137, in remove
raise NotImplementedError('cannot remove artist')
NotImplementedError: cannot remove artist
Is there any other way to do this?

You can remove a the figtext using the code below, assuming your figtext object has been saved to a variable t.
plt.gcf().texts.remove(t)
plt.draw()
plt.gcf() will get the current figure object. If you already have the figure object, say for example you created it with fig = plt.figure() before doing your plotting, then you can just use fig.texts.remove(t).
You need to call plt.draw() after you have removed the object to re-draw the plot and hence show the removal.

Related

Pyglet - TypeError: expected string or buffer

I'm trying to use pyglet instead of pygame, 'cause it supports several screens.
this is a sample code that I run:
import pyglet
display = pyglet.canvas.get_display()
screens = display.get_screens()
window = pyglet.window.Window(fullscreen=True, screen=screens[1])
pyglet.app.run()
and I get this error:
Traceback (most recent call last): File
"/home/pi/netcomShopTV/idk.py", line 5, in
window = pyglet.window.Window() File "/usr/local/lib/python2.7/dist-packages/pyglet/init.py", line 359,
in getattr
import(import_name) File "/usr/local/lib/python2.7/dist-packages/pyglet/window/init.py",
line 1890, in
gl._create_shadow_window() File "/usr/local/lib/python2.7/dist-packages/pyglet/gl/init.py", line
209, in _create_shadow_window
_shadow_window = Window(width=1, height=1, visible=False) File "/usr/local/lib/python2.7/dist-packages/pyglet/window/xlib/init.py",
line 171, in init
super(XlibWindow, self).init(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/pyglet/window/init.py",
line 642, in init
self._create() File "/usr/local/lib/python2.7/dist-packages/pyglet/window/xlib/init.py",
line 265, in _create
self.context.set_vsync(self._vsync) # XXX ? File "/usr/local/lib/python2.7/dist-packages/pyglet/gl/xlib.py", line 265,
in set_vsync
warnings.warn(e) TypeError: expected string or buffer
Pyglet Version: 1.4.8
I searched in internet, couldn't find anything to solve this problem.
It seems this bug was introduced with this recent change. You should definitely raise it on pyglet github issue tracker.
Meanwhile, try installing the version prior to 1.4.8. (I though suspect this may just lead to crashing on failed sync as opposed to trying to warn you and then crashing :)).
As #alecxe mentioned, it was a bug. After I opened a ticket on github, I got the solution:
This is an exception for a Raspberry Pi specific issue. It's supposed
to raise a warning, and pass without crashing. If possible, could you
try editing line 265 in
/usr/local/lib/python2.7/dist-packages/pyglet/gl/xlib.py, and
changing:
warnings.warn(e) to warnings.warn(e.message)

_tkinter.TclError: invalid command name "table"

I tried to use tktable package to create table and show my data.
However, I could not make it work.
import Tkinter
import tktable
root = Tkinter.Tk()
table = tktable.Table(root, rows=10, cols=4)
table.pack(side="top", fill="both", expand=True)
root.mainloop()
I got error like:
Traceback (most recent call last):
File "C:/Users/jgou/PycharmProjects/mmt-autobench/autobench/test/test.py",
line 520, in <module> table = Table(root, rows=10, cols=4)
File "C:\Users\jgou\PycharmProjects\mmtautobench\autobench\inst\tktable.py",
line 135, in __init__tkinter.Widget.__init__(self, master, 'table', kw)
File "C:\Users\jgou\AppData\Local\Continuum\Anaconda2\lib\libtk\Tkinter.py",
line 2096, in __init__(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: invalid command name "table"
I searched online and could you solve the issue, please suggest and help. It made me crazy. It should be very easy. Thank you very much.

%matplotlib inline ValueError

When I use %matplotlib inline in my program, I get a ValueError. What does this error mean, and how can I resolve it?
Here is the error:
Traceback (most recent call last):
File "main.py", line 40, in <module>
ct.iloc[:-1,:-1].plot(kind='bar',stacked=True,color=['red','blue'],grid='false')
File "/usr/lib/python2.7/dist-packages/pandas/tools/plotting.py", line 1735, in plot_frame
plot_obj.generate()
File "/usr/lib/python2.7/dist-packages/pandas/tools/plotting.py", line 907, in generate
self._adorn_subplots()
File "/usr/lib/python2.7/dist-packages/pandas/tools/plotting.py", line 1012, in _adorn_subplots
ax.grid(self.grid)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 2176, in grid
b = _string_to_bool(b)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 54, in _string_to_bool
raise ValueError("string argument must be either 'on' or 'off'")
ValueError: string argument must be either 'on' or 'off'
When asking a question you should follow these guidlines: https://stackoverflow.com/help/mcve
instead of just posting a traceback.
That said tracebacks can be very useful and following yours you'll be able to figure out the problem.
Using the final line of your traceback can be very useful. One of the string arguments you are passing should only be 'on' or 'off'. Based on this we can then look at the grid option as this is a boolean option.
I tested this like so:
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([23,4],[4,6])
plt.grid('false')
giving the same error you got.
To fix this you should use either grid = 'off' or grid = False as options. In my example above I would change that to plt.grid('off')

IndexError: too many indices on Python

Using PyDev with an eclipse environment for Python 2.7 on OSX. Trying to count the element in the array and sum up the elements in the array. Getting an error on the index.
import numpy as np
import os
import sys
csv_file_object = fileName = os.path.join('train.csv')
print('Directory separator on your platform ({}): {}'.format(sys.platform, os.sep))
data=[]
for row in csv_file_object:
data.append(row)
data = np.array(data)
number_passengers = np.size(data[0::,0].astype(np.float))
number_survived = np.sum(data[0::,0].astype(np.float))
proportion_survivors = number_survived / number_passengers
Traceback (most recent call last):
File "/Users/scdavis6/Documents/Kaggle/Titanic1.py", line 14, in <module>
number_passengers = np.size(data[0::,0].astype(np.float))
IndexError: too many indices
Let me know if I can provide additional information.
Thank you.
Update:
I made the edits, but got another error about the module not being callable:
Traceback (most recent call last):
File "/Users/scdavis6/Documents/Kaggle/Titanic1.py", line 5, in <module>
csv_file_object = fileName = os.path('train.csv')
TypeError: 'module' object is not callable
Update:
I changed os.path('train.csv') to os.path.join('train.csv'), but got another error about not finding the .csv file.
Traceback (most recent call last):
File "/Users/scdavis6/Documents/Kaggle/Titanic1.py", line 9, in <module>
with open(fileName) as f:
IOError: [Errno 2] No such file or directory: 'train.csv'
Here's the absolute path for the .csv file and the python scripts.
import os
os.path.abspath("/Users/scdavis6/Desktop/train.csv")
'/Users/scdavis6/Desktop/train.csv'
import os
os.path.abspath("/Users/scdavis6/Documents/Kaggle/Titanic1.py")
'/Users/scdavis6/Documents/Kaggle/Titanic1.py'
Assuming that this is your actual code, the problem is that you never open the file. Your csv_file_object is still just the fileName, and thus your data is made up of the characters of that file name, resulting in a 1D numpy array.
Instead, you should open the file and create a csv.reader for it.
import csv
with open(fileName) as f:
reader = csv.reader(f)
data=[]
for row in reader:
data.append(row)
data = np.array(data)
Or shorter: data = np.array([row for row in csv.reader(f)])
Update: The new error you are getting is probably due to you accidentally changing
os.path.join('train.csv') to os.path('train.csv'), i.e., instead of calling the join function from the os.path module, you are (trying to) call the module itself.
Update: It seems your train.csv file is not in the same directory as your Python script, thus the script won't find the file if you just use the filename. You have to use the absolute path together with the filename:
fileName = os.path.join('/Users/scdavis6/Desktop', 'train.csv')
Or just fileName = '/Users/scdavis6/Desktop/train.csv'. Alternatively, move your train.csv file to the same directory as your Python script. This might indeed be the better and more robust option, unless you are using this file in multiple scripts in different directories.

django-cumulus: retrieve PIL.Image object from django.db.models.ImageField

I'm using django-cumulus to store my media on Rackspace cloud.
I need to retrieve data from ImageField to PIL.Image. I need it to make some changes on this image (cropping, filters, etc.) and save it to another cumulus ImageField.
I tried this code:
def field_to_image(field):
# field - cumulus-powered ImageField on some model
from StringIO import StringIO
from PIL import Image
r = field.read() # ERROR throws here!
image = Image.open(StringIO(r))
return image
It worked good on half of my files, but on the other half I'm always getting this error:
Traceback (most recent call last):
File "tmp.py", line 78, in <module>
resize_photos(start)
File "tmp.py", line 59, in resize_photos
photo.make_thumbs()
File "/hosting/site/news/models.py", line 65, in make_thumbs
i = functions.field_to_image(self.img)
File "/hosting/site/functions.py", line 169, in field_to_image
r = field.read()
File "/usr/local/lib/python2.7/dist-packages/cumulus/storage.py", line 352, in read
if self._pos == self._get_size() or chunk_size == 0:
File "/usr/local/lib/python2.7/dist-packages/cumulus/storage.py", line 322, in _get_size
self._size = self._storage.size(self.name)
File "/usr/local/lib/python2.7/dist-packages/cumulus/storage.py", line 244, in size
return self._get_object(name).total_bytes
AttributeError: 'bool' object has no attribute 'total_bytes'
Can anyone help me? Maybe there is the better way to retrieve PIL.Image object from rackspace?
The file I'm trying to read() exists and is available via url on Rackspace
It returns False if the file is not found in the container, hence is a very confusing error.
It is fixed now in repo, but still not in the released version: it returns None instead of False:
https://github.com/django-cumulus/django-cumulus/blob/master/cumulus/storage.py#L203
But the basic cause of the problem: the file is not found.