Storing pyplot object in variable - python-2.7

Please refer to the following code.
>>> p = plt.plot(year, rank)
>>> p.show()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'show'
>>> plt.plot(year, rank)
[<matplotlib.lines.Line2D object at 0x7f3b56443890>]
>>> plt.show()
When I try to store plt in a variable p, it showing the AttributeError:
But when directly use plt.show(), it's working. I am not able to understand the difference.
I am using python 2.7 in Ubuntu 16.4, and running the program from terminal.

plt.plot(x,y) returns a list of Line2D objects. You store this list in a variable p. As the error tells you, 'list' object has no attribute 'show'. This can be taken literally, because show() is a function in the matplotlib.pyplot module and any normal python list does not even know about the existence of matplotlib.
You may of course still store the list in a variable, but in order to show the plot you need to use plt.show() independent of where you stored the return of any plotting commands
import matplotlib.pyplot as plt
p = plt.plot(x,y)
plt.show()

Related

Run Matlab script from Python: TypeError: 'float' object is not iterable

Actually I have a problem when calling a Matlab script from Python.
import matlab.engine
import os
import random
import numpy as np
a=[str(random.randint(1,3)) for _ in range(3)]
print(a)
eng=matlab.engine.start_matlab()
eng.cd("/Users/dha/Documents/MATLAB/test-matlab/",nargout=0)
sr, state=eng.test_func()
print(sr)
print(state)
In fact I want to return "sr" which is a float and an array of integer "state", e.g. sr = 34.31 and state = [1,2,5]. The function test_func() work well on Matlab, but when I run this in Python from terminal (python test_matlab_engine.py) I received the following error:
Traceback (most recent call last):
File "test_matlab_engine.py", line 10, in <module>
sr, state=eng.mabuc_drl(a)
TypeError: 'float' object is not iterable
Anyone please give me the solution. Thank you so much in advance.
It seems that the result from MATLAB to Python has been cut off. If you have two parameters, you only get one which is the first parameter from the MATLAB. So, the question is how to get two or more parameters.
In a word, you should write this in your Python file:
re = eng.your_function_name(parameter1, parameter2, nargout=2)
where re contains two parameters which come from MATLAB.
You can find more information in the official documentation: Call MATLAB Functions from Python

Pickle figures from matplotlib: 2

Following Pickle figures from matplotlib, I am trying to load a figure from a pickle. I am using the same code with the modifications that are suggested in the responses.
Saving script:
import numpy as np
import matplotlib.pyplot as plt
import pickle as pl
# Plot simple sinus function
fig_handle = plt.figure()
x = np.linspace(0,2*np.pi)
y = np.sin(x)
plt.plot(x,y)
# plt.show()
# Save figure handle to disk
pl.dump(fig_handle,file('sinus.pickle','wb'))
Loading script:
import matplotlib.pyplot as plt
import pickle as pl
import numpy as np
# Load figure from disk and display
fig_handle = pl.load(open('sinus.pickle', 'rb'))
fig_handle.show()
The saving script produces a file named "sinus.pickle" but the loading file does not show the anticipated figure. Any suggestions?
Python 2.7.13
matplotlib 2.0.0
numpy 1.12.1
p.s. following a suggestion replaced fig_handle.show() with pat.show() which produced an error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/
site-packages/matplotlib/backends/backend_macosx.py", line 109,
in_set_device_scale
self.figure.dpi = self.figure.dpi / self._device_scale * value
File "/usr/local/lib/python2.7/site-packages/matplotlib/figure.py",
line 416, in _set_dpi
self.callbacks.process('dpi_changed', self)
File "/usr/local/lib/python2.7/site-packages/matplotlib/cbook.py",
line 546, in process
if s in self.callbacks:
AttributeError: 'CallbackRegistry' object has no attribute 'callbacks'
What you call your "loading script" doesn't make any sense.
From the very link that you provided in your question, loading the picked figure is as simple as:
# Load figure from disk and display
fig_handle2 = pl.load(open('sinus.pickle','rb'))
fig_handle2.show()
Final solution included modification of
fig_handle.show()
to
plt.show()
and modification of the backend to "TkAgg", based to an advice given by ImportanceOfBeingErnest

Invalid chart type given box

Here is my code
from pandas import read_csv
from pandas.tools.plotting import scatter_matrix
from matplotlib import pyplot
filename = 'iris.data.csv'
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
dataset = read_csv(filename, names=names)
print(dataset.shape)
print(dataset.head(20))
# Data visualizations
dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)
pyplot.show()
When i run above code. Then following error is shown
Traceback (most recent call last):
File "/media/k/UBUNTU2/Work and stuff/coding language/Python/Machine learning/exp.py", line 43, in <module>
dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)
File "/usr/local/lib/python2.7/dist-packages/pandas/tools/plotting.py", line 2090, in plot_frame
raise ValueError('Invalid chart type given %s' % kind)
ValueError: Invalid chart type given box
Any idea ? What should i do? Please help
Your pandas version (0.14) is already 3 years old. The "box" kind was introduced in version 0.15. Now we are at version 0.20.
The solution is thus to install a newer version of pandas in order to be able to use kind="box" in the plotting wrapper.
If you need to use version 0.14 you can get boxplot using the DataFrame.boxplot() method. The usage according to documentation would be:
df = DataFrame(rand(10,5))
plt.figure();
bp = df.boxplot()

Keras:Vgg16 -- Error in `decode_predictions'

I am trying to perform an image classification task using a pre-trained VGG16 model in Keras. The code I wrote, following the instructions in the Keras application page, is:
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input, decode_predictions
import numpy as np
model = VGG16(weights='imagenet', include_top=True)
img_path = './train/cat.1.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
features = model.predict(x)
(inID, label) = decode_predictions(features)[0]
which is quite similar to the code shown in this question already asked in the forum. But in spite of having the include_top parameter as True, I am getting the following error:
Traceback (most recent call last):
File "vgg16-keras-classifier.py", line 14, in <module>
(inID, label) = decode_predictions(features)[0]
ValueError: too many values to unpack
Any help will be deeply appreciated! Thanks!
It's because (according to a function definition which might be found here) a function decode_predictions returns a triple (class_name, class_description, score). This why it claims that there are too many values to unpack.

Error with GDAL

I have tried and run this script from Rutger Kassies.
import gdal
import matplotlib.pyplot as plt
ds = gdal.Open('HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01')
data = ds.ReadAsArray()
ds = None
fig, ax = plt.subplots(figsize=(6,6))
ax.imshow(data[0,:,:], cmap=plt.cm.Greys, vmin=1000, vmax=6000)
But then an error always occured:
Traceback (most recent call last):
File "D:\path\to\python\stackoverflow.py", line 5, in <module>
data = ds.ReadAsArray()
AttributeError: 'NoneType' object has no attribute 'ReadAsArray'
What's wrong with the script? Am I missing something? In installing GDAL I have followed this instruction http://pythongisandstuff.wordpress.com/2011/07/07/installing-gdal-and-ogr-for-python-on-windows/
Am using windows 7/32 bit/Python 2.7.
Thanks!
gdal.Open() is failing and returning 'None'. This produces the sometimes counterintuitive message "NoneType' object has no attribute ...". Quoting from Python: Attribute Error - 'NoneType' object has no attribute 'something', "NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result."
Apparently GDAL is correctly installed. It could be that the file is not readable or that there is an issue with the HDF driver. Are you getting any error message like:
`HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01' does not
exist in the file system, and is not recognised as a supported dataset
name.
To get additional information you can try something like this instead of the gdal.Open() line in your script:
gdal.UseExceptions()
ds=None
try:
ds = gdal.Open('HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01')
except RuntimeError, err:
print "Exception: ", err
exit(1)
Also, there's an extra '}' at the end of the script.
By default, osgeo.gdal returns None on error, and does not normally raise informative exceptions. You can change this with gdal.UseExceptions().
Try something like this:
from osgeo import gdal
gdal.UseExceptions()
source_path = r'HDF4_SDS:sample:"D:\path\to\file\A2002037045000.L2_LAC.SAMPLE.hdf":01'
try:
ds = gdal.Open(source_path)
except RuntimeError as ex:
raise IOError(ex)
The last bit just re-raises the exception as an IOError rather than a RuntimeException.
The solution is to modify source_path to a working path to your data source, e.g., I see
IOError: `HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01' does not exist in the file system, and is not recognised as a supported dataset name.