Python 2.7 Unrecognized Character G in format string during runtime - string

I have Python 2.7 Win 32 and have installed Matplotlib, Numpy, PyParsing, Dateutil. In IDLE I place in the code:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np
def graphRawFX () :
date=mdates.strpdate2num('%Y%m%d%H%M%S')
bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')
delimiter=',',
converters={0:mdates.strpdate2num('%Y%m%d%H%M%S') }
fig = plt.figure(figsize=(10,7))
ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)
ax1.plot(date,bid)
ax1.plot(date,ask)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
plt.grid(True)
plt.show()
I then proceed to enter:
rawGraphFX()
This results into the error below:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
graphRawFX()
File "C:/Users/Emanuel/Desktop/graph", line 16, in graphRawFX
ax1.plot(date,ask)
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 4137, in plot
for line in self._get_lines(*args, **kwargs):
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 317, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 276, in _plot_args
linestyle, marker, color = _process_plot_format(tup[-1])
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 129, in _process_plot_format
'Unrecognized character %c in format string' % c)
ValueError: Unrecognized character G in format string
>>>
This is probably easy to fix but I need help since I'm getting frustrated over this.

There are at least two issues with these two lines:
date=mdates.strpdate2num('%Y%m%d%H%M%S')
bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')
The first of these lines sets date to a class instance that would convert strings to matplotlib style dates. However, you never supply the dates. You need to come up with date strings from somewhere and apply this function to them.
The second line of these lines makes two assignments. It first assigns np.loadtxt to True and unpack to 'GPBUSD1d.txt'. It consequently assigns bid to True and ask to 'GPBUSD1d.txt'. It is the latter that causes the Unrecognized character error when matplotlib tries to interpret the G in 'GPBUSD1d.txt' as some kind of format instruction. You probably intended something like:
bid, ask = np.loadtxt('GPBUSD1d.txt', unpack=True)
This would call the function np.loadtxt which would load the file GPBUSD1d.txt' and transpose ("unpack") it.

Related

TypeError: float() argument must be a string or a number, not 'datetime.timedelta'

I want to make a plot with the data am fetching from the database, voltage(float), and time(time), I was getting the error now am stack. please help or is there a best way I can go about it.?
import matplotlib.pyplot as plt
import numpy as np
import serial as ser
import time
import datetime
import mysql.connector
my_connect = mysql.connector.connect(host="localhost", user="Kennedy", passwd="Kennerdol05071994", database="ecg_db", auth_plugin="mysql_native_password")
mycursor = my_connect.cursor()
voltage_container = []
time_container = []
def fetch_voltage():
pat_id = 1
query = "SELECT voltage, time FROM ecg_data_tbl where patient_id = 1 "
mycursor.execute(query)
result = mycursor .fetchall()
voltage, time = list(zip(*result))
for volts in voltage:
voltage_container.append(volts)
voltage_data = np.array(voltage_container)
for tim in time:
time_container.append(tim)
time_data = np.array(time_container)
plt.plot(time_data, voltage_data)
fetch_voltage()
I was told to convert them to arrays which I did but nothing is changing. The error am getting is:
Traceback (most recent call last):
File "C:\Users\Kennedy Mulenga\Desktop\Level 5\18136709_BIT_280_Arduino_ECG_Project\fetch_all.py", line 31, in <module>
fetch_voltage()
File "C:\Users\Kennedy Mulenga\Desktop\Level 5\18136709_BIT_280_Arduino_ECG_Project\fetch_all.py", line 28, in fetch_voltage
plt.plot(time_data, voltage_data)
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\pyplot.py", line 3019, in plot
return gca().plot(
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_axes.py", line 1607, in plot
self.add_line(line)
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_base.py", line 2101, in add_line
self._update_line_limits(line)
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_base.py", line 2123, in _update_line_limits
path = line.get_path()
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\lines.py", line 1022, in get_path
self.recache()
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\lines.py", line 663, in recache
x = _to_unmasked_float_array(xconv).ravel()
File "C:\Users\Kennedy Mulenga\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\cbook\__init__.py", line 1333, in _to_unmasked_float_array
return np.asarray(x, float)
TypeError: float() argument must be a string or a number, not 'datetime.timedelta'
Your time data is not a type matplotlib is familiar with so it's trying to convert it itself and it can't. Instead make it a type it can handle yourself.
A common choice, for example, would be
for tim in time:
time_container.append(tim.total_seconds())
time_data = np.array(time_container)
Now you are using the total number of seconds in your datetime.timedelta object (that is the result of your query). This is a float so matplotlib can plot it. If you don't want total seconds you can look at the docs for other options.
https://docs.python.org/3/library/datetime.html

' ValueError: max() arg is an empty sequence ' when using plt.show() in PyCharm

enter image description hereI'm learning how to using python to draw some 3D pictures.
When I typing plt.show(), there will be an error.
ValueError: max() arg is an empty sequence
However, I have tried run it on IDLE and it didn't have an error.
What should I do to fix this problem when using PyCharm, really appreciate for helping.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-6 * np.pi, 6 * np.pi, 1000)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot(x, y, z)
plt.show()
I tried it in Python Console, only when I run plt.show() there will be an error.
[<mpl_toolkits.mplot3d.art3d.Line3D at 0x111b09c88>]
plt.show()
/Users/harry./Library/Python/3.6/lib/python/site-packages/matplotlib/figure.py:1743: UserWarning: This figure includes Axes that are not compatible with tight_layout, so its results might be incorrect.
warnings.warn("This figure includes Axes that are not "
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3267, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-6-1eb00ff78cf2>", line 1, in <module>
plt.show()
File "/Users/harry./Library/Python/3.6/lib/python/site-packages/matplotlib/pyplot.py", line 253, in show
return _show(*args, **kw)
File "/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend/backend_interagg.py", line 27, in __call__
manager.show(**kwargs)
File "/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend/backend_interagg.py", line 99, in show
self.canvas.show()
File "/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend/backend_interagg.py", line 64, in show
self.figure.tight_layout()
File "/Users/harry./Library/Python/3.6/lib/python/site-packages/matplotlib/figure.py", line 1753, in tight_layout
rect=rect)
File "/Users/harry./Library/Python/3.6/lib/python/site-packages/matplotlib/tight_layout.py", line 326, in get_tight_layout_figure
max_nrows = max(nrows_list)
ValueError: max() arg is an empty sequence

Y = churn.iloc[:, 18].values

Trying to import my dataset(18 columns counting from 0) i got this error:
File "C:/Users/ASUS/PycharmProjects/PA/BestAcc.py", line 23, in
Y = churn.iloc[:, 18].values File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 1472, in
getitem
return self._getitem_tuple(key) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 2013, in
_getitem_tuple
self._has_valid_tuple(tup) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 222, in
_has_valid_tuple
self._validate_key(k, i) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 1957, in
_validate_key
self._validate_integer(key, axis) File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 2009, in
_validate_integer
raise IndexError("single positional indexer is out-of-bounds") IndexError: single positional indexer is out-of-bounds
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
churn = pd.read_csv("HR.csv")
#import colums except the first one in the dataset
X = churn.iloc[:, 1:18].values
Y = churn.iloc[:, 18].values
iloc has been deprecated in later versions of pandas - I would suggest using loc instead -
X = churn.loc[:, churn.columns[1:18]]
Y = churn.loc[:, churn.columns[18]]

Python Error (ValueError: _getfullpathname: embedded null character)

I don't know How to fix it please help, I have tried everything mentioned in the post Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC) but no luck. I'm a newbie to the python and am self learning specific details would greatly be appreciated.
Console:
Traceback (most recent call last):
from matplotlib import pyplot
File "C:\Users\...\lib\site-packages\matplotlib\pyplot.py", line 29, in <module>
import matplotlib.colorbar
File "C:\Users\...\lib\site-packages\matplotlib\colorbar.py", line 34, in <module>
import matplotlib.collections as collections
File "C:\Users\...\lib\site-packages\matplotlib\collections.py", line 27, in <module>
import matplotlib.backend_bases as backend_bases
File "C:\Users\...\lib\site-packages\matplotlib\backend_bases.py", line 62, in <module>
import matplotlib.textpath as textpath
File "C:\Users\...\lib\site-packages\matplotlib\textpath.py", line 15, in <module>
import matplotlib.font_manager as font_manager
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1421, in <module>
_rebuild()
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1406, in _rebuild
fontManager = FontManager()
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1044, in __init__
self.ttffiles = findSystemFonts(paths) + findSystemFonts()
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 313, in findSystemFonts
for f in win32InstalledFonts(fontdir):
File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 231, in win32InstalledFonts
direc = os.path.abspath(direc).lower()
File "C:\Users\...\lib\ntpath.py", line 535, in abspath
path = _getfullpathname(path)
ValueError: _getfullpathname: embedded null character
Python:
importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing dataset
dataset = pd.read_csv('Position_Salaries.csv')
x = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2].values
#Linear Regression
from sklearn.linear_model import LinearRegression
reg_lin = LinearRegression()
reg_lin = reg_lin.fit(x,y)
#ploynomial Linear Regression
from sklearn.preprocessing import PolynomialFeatures
reg_poly = PolynomialFeatures(degree = 3)
x_poly = reg_poly.fit_transform(x)
reg_poly.fit(x_poly,y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(x_poly,y)
#Visualizing Linear Regression results
plt.scatter(x,y,color = 'red')
plt.plot(x,reg_lin.predict(x), color = 'blue')
plt.title('Truth vs. Bluff (Linear Reg)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
#Visualizing Polynomial Regression results
plt.scatter(x,y,color = 'red')
plt.plot(x,lin_reg_2.predict(reg_poly.fit_transform(x)), color = 'blue')
plt.title('Truth vs. Bluff (Linear Reg)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
To find this in font_manager py:
direc = os.path.abspath(direc).lower()
change it into:
direc = direc.split('\0', 1)[0]
and save to apply in your file.
I don't think you applied the patch in Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC) correctly: if you had, there shouldn't be a mention of direc = os.path.abspath(direc).lower() in your error stack, since the patch removed it.
To be clear, here is the entire win32InstalledFonts() method in C:\Anaconda\envs\py35\Lib\site-packages\matplotlib\font_manager.py (or wherever Anaconda is installed) after the patch is applied, with matplotlib 2.0.0:
def win32InstalledFonts(directory=None, fontext='ttf'):
"""
Search for fonts in the specified font directory, or use the
system directories if none given. A list of TrueType font
filenames are returned by default, or AFM fonts if *fontext* ==
'afm'.
"""
from six.moves import winreg
if directory is None:
directory = win32FontDirectory()
fontext = get_fontext_synonyms(fontext)
key, items = None, {}
for fontdir in MSFontDirectories:
try:
local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir)
except OSError:
continue
if not local:
return list_fonts(directory, fontext)
try:
for j in range(winreg.QueryInfoKey(local)[1]):
try:
''' Patch fixing [Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC)](https://stackoverflow.com/a/34007642/395857)
key, direc, any = winreg.EnumValue( local, j)
if not is_string_like(direc):
continue
if not os.path.dirname(direc):
direc = os.path.join(directory, direc)
direc = os.path.abspath(direc).lower()
'''
key, direc, any = winreg.EnumValue( local, j)
if not is_string_like(direc):
continue
if not os.path.dirname(direc):
direc = os.path.join(directory, direc)
direc = direc.split('\0', 1)[0]
if os.path.splitext(direc)[1][1:] in fontext:
items[direc] = 1
except EnvironmentError:
continue
except WindowsError:
continue
except MemoryError:
continue
return list(six.iterkeys(items))
finally:
winreg.CloseKey(local)
return None
The actual cause of the issue appears to be in os.path.abspath(). A better solution might be to edit <python dir>\Lib\ntpaths.py as detailed in Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC)
Basically, add a ValueError: exception handler to the Windows version of the abspath() function. This is lower down on the call stack and could save you from encountering this issue in other places.

Type Error when I try to make a 3D graph in python

I know how to make 3D-graph in Python but for this one I have an error I've never seen. I want to have the graph of :
$$f(x,y)=\frac{8\cos(\sqrt{x^2+y^2}}{\sqrt{1+x^2+y^2}}$$ (LaTeX doesn't work here... ???)
My code :
import math
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
ax = Axes3D(plt.figure())
def f(x,y):
return (8*math.cos(math.sqrt(x**2+y**2)))/(math.sqrt(1+x**2+y**2))
X = np.arange(-1,1,0.1)
Y = np.arange(-1,1,0.1)
X,Y=np.meshgrid(X,Y)
Z=f(X,Y)
ax.plot_surface(X,Y,Z)
plt.show()
The error :
runfile('C:/Users/Asus/Desktop/Informatiques/nodgim.py', wdir=r'C:/Users/Asus/Desktop/Informatiques')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Asus\Desktop\WinPython\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 680, in runfile
execfile(filename, namespace)
File "C:\Users\Asus\Desktop\WinPython\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Asus/Desktop/Informatiques/nodgim.py", line 22, in <module>
Z=f(X,Y)
File "C:/Users/Asus/Desktop/Informatiques/nodgim.py", line 16, in f
return (8*math.cos(math.sqrt(x**2+y**2)))/(math.sqrt(1+x**2+y**2))
TypeError: only length-1 arrays can be converted to Python scalars
Can you explain me what I have to do?
Thank you in advance
math.cos and math.sqrt expect to get a scalar value but instead were passed an array type that they cannot handle properly which results in your type error. Essentially Python's built in math functions don't know how to deal with numpy arrays, so to fix this you need to use the mathematical functions that numpy provides to work on these data types: numpy.cos and numpy.sqrt
This will then give you the vectorization you need.

Resources