%matplotlib inline ValueError - python-2.7

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')

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)

TensorVariable to Array

I'm trying to evaluate a theano TensorValue expression:
import pymc3
import numpy as np
with pymc3.Model():
growth = pymc3.Normal('growth_%s' % 'some_name', 0, 10)
x = np.arange(4)
(x * growth).eval()
but get the error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/danna/.virtualenvs/lib/python2.7/site-packages/theano/gof/graph.py", line 522, in eval
self._fn_cache[inputs] = theano.function(inputs, self)
File "/home/danna/.virtualenvs/lib/python2.7/site-packages/theano/compile/function.py", line 317, in function
output_keys=output_keys)
File "/home/danna/.virtualenvs/lib/python2.7/site-packages/theano/compile/pfunc.py", line 486, in pfunc
output_keys=output_keys)
File "/home/danna/.virtualenvs/lib/python2.7/site-packages/theano/compile/function_module.py", line 1839, in orig_function
name=name)
File "/home/danna/.virtualenvs/lib/python2.7/site-packages/theano/compile/function_module.py", line 1487, in __init__
accept_inplace)
File "/home/danna/.virtualenvs/lib/python2.7/site-packages/theano/compile/function_module.py", line 181, in std_fgraph
update_mapping=update_mapping)
File "/home/danna/.virtualenvs/lib/python2.7/site-packages/theano/gof/fg.py", line 175, in __init__
self.__import_r__(output, reason="init")
File "/home/danna/.virtualenvs/lib/python2.7/site-packages/theano/gof/fg.py", line 346, in __import_r__
self.__import__(variable.owner, reason=reason)
File "/home/danna/.virtualenvs/lib/python2.7/site-packages/theano/gof/fg.py", line 391, in __import__
raise MissingInputError(error_msg, variable=r)
theano.gof.fg.MissingInputError: Input 0 of the graph (indices start from 0), used to compute InplaceDimShuffle{x}(growth_some_name), was not provided and not given a value. Use the Theano flag exception_verbosity='high', for more information on this error.
I tried
Can someone please help me see what the theano variables actually output?
Thank you!
I'm using Python 2.7 and theano 1.0.3
While PyMC3 distributions are TensorVariable objects, they don't technical have any values to be evaluated outside of sampling. If you want values, you have to at least run sampling on the model:
with pymc3.Model():
growth = pymc3.Normal('growth', 0, 10)
trace = pymc3.sample(10)
x = np.arange(4)
x[:, np.newaxis]*trace['growth']
If you want to view node values during sampling, you'd need to use theano.tensor.printing.Print objects. For more info, see the PyMC3 debugging tips.

How to print the help (usage) section for the main parser of Argparse and not the usage of a subparser?

I have been writing a command line programs with Argparse for some time now, and I am trying to write it in such a way that when the user supplies the following to the command line:
$python my_script.py -h
A help section (usage) will be printed out that prints out help section of the main parser, as well as brief overviews of the subparsers.
But right now, anytime I type in the previous line into my terminal, I receive no usage and instead get a massive traceback and the following error:
TypeError: expected string or buffer
This error has never occurred to me before with argparse-based command line programs. Furthermore, if I supply the name of one of the subparsers,
$python my_script.py subparserA -h
I get a print-out of the subparser's usage. The same holds true for other subparsers.
So why is it not possible for me to get the usage for the main parser? This worked for me before so I don't know why it's not working now. I really would like for the user to be able to look at an overview of the different subparsers available.
My basic code is currently set up in the following way:
import argparse
import sys
if __name__ == "__main__":
Parser = argparse.ArgumentParser(prog= "My_program")
Parser.description= "This program does A and B things."
subparsers= Parser.add_subparsers(help= "SubparserA does A things and SubparserB does B things", dest='mode')
subparserA= subparsers.add_parser("subparserA", help= "Additional explanation of what A things entail")
subparserA.add_arguments("-foo", required=True, help= "foo is needed for SubparserA to work")
subparserB= subparsers.add_parser("subparserB", help="Additional explanation of what B things entail")
subparserB.add_argument("-bar", required=True, help= "bar is needed for SubparserB to work")
args= Parser.parse_args()
if args.mode == "subparserA":
###do things pertinent to subparserA
elif args.mode== "subparserB":
###do things pertinent to subparserB
else:
argparse.print_help()
argparse.ArgumentError("too few arguments")
UPDATE
Here is the full traceback of the error:
Traceback (most recent call last):
File "my_program.py", line 164, in <module>
args= Parser.parse_args()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1701, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1733, in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1939, in _parse_known_args
start_index = consume_optional(start_index)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1879, in consume_optional
take_action(action, args, option_string)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1807, in take_action
action(self, namespace, argument_values, option_string)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 996, in __call__
parser.print_help()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 2340, in print_help
self._print_message(self.format_help(), file)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 2314, in format_help
return formatter.format_help()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 281, in format_help
help = self._root_section.format_help()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 211, in format_help
func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 485, in _format_text
return self._fill_text(text, text_width, indent) + '\n\n'
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 621, in _fill_text
text = self._whitespace_matcher.sub(' ', text).strip()
TypeError: expected string or buffer
You should be using
Parser.print_help()
Parser.error('too few arguments')
That is use methods of the existing Parser object.
When I run your script
1019:~/mypy$ python stack46754855.py
Traceback (most recent call last):
File "stack46754855.py", line 10, in <module>
subparserA= subparsers.add_parser("subparserA", help= "Additional explanation of what A things entail", dest= 'mode')
File "/usr/lib/python2.7/argparse.py", line 1066, in add_parser
parser = self._parser_class(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'dest'
dest is a not a valid parameter for the add_parser method. It is a valid, and useful, parameter for add_subparsers.
subparsers= Parser.add_subparsers(dest='mode')
It also objects to the add_arguments method.
After correction those I get:
1022:~/mypy$ python stack46754855.py
usage: My_program [-h] {subparserA,subparserB} ...
My_program: error: too few arguments
In Py2, subparsers is a required argument. It is optional in Py3 (a bug), allowing the script to run to the invalid argparse.print_help call:
1022:~/mypy$ python3 stack46754855.py
Traceback (most recent call last):
File "stack46754855.py", line 27, in <module>
argparse.print_help()
AttributeError: module 'argparse' has no attribute 'print_help'
With the change I suggested above:
1025:~/mypy$ python3 stack46754855.py
usage: My_program [-h] {subparserA,subparserB} ...
This program does A and B things.
positional arguments:
{subparserA,subparserB}
SubparserA does A things and SubparserB does B things
subparserA Additional explanation of what A things entail
subparserB Additional explanation of what B things entail
optional arguments:
-h, --help show this help message and exit
usage: My_program [-h] {subparserA,subparserB} ...
My_program: error: too few arguments
The second usage comes from the Parser.error call.
I can't reproduce your
massive traceback and the following error:
TypeError: expected string or buffer
I need to see that traceback (or part of it) to see what exactly is raising the error. That's not a normal argparse error; certainly it isn't one that argparse traps and reroutes.
More on the required/not required subparser behavior at How to Set a Default Subparser using Argparse Module with Python 2.7
Use + instead of , for multi line help string in parser.add_argument. If you have split you argument help in multiple lines using ',' then, you will see this issue
parser.add_argument("xml",help=("long help here",
" long help second line"))
This will result in above exception
instead
parser.add_argument("xml",help=("long help here" +
" long help second line"))

Accessing a csv file in python

I keep getting an "invalid keyword" error when i try to read from a csv file in python. Any ideas for a work around for this?
C:\Python27\python.exe C:/Users/User_Name/PycharmProjects/untitled/car.py
Traceback (most recent call last): File
"C:/Users/User_Name/PycharmProjects/untitled/car.py", line 122, in <module> d = handle_refugee_data.DataTable(csvformat="generic", data_directory="car2014", start_date="2013-12-01") File
"C:\Users\User_Name\PycharmProjects\untitled\handle_refugee_data.py", line 78, in __init__ with open("%s/%s" % (data_directory, data_layout), newline='') as csvfile:
TypeError: 'newline' is an invalid keyword argument for this function
Process finished with exit code 1
========================================================================
newline is a valid keyword argument to open() in Python 3, but not in Python 2, which appears to be what you are using.
One solution, if possible, would be to execute the script with Python 3 instead. Alternatively, as pointed out by #dhke in the comments, you could use io.open() instead, which does accept a newline keyword argument.
Of course, you could probably use the csv module instead, depending on your use case (which is not clear from the original question).

Update figure text in matplotlib figure in python

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.