matplotlib's contourf producing error in tikzplotlib - python

could someone point out to what is wrong with the following code?
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm,colors
import tikzplotlib
max_r = 20
N_vorfs = 500
scalings = np.linspace(0.1, 5.*np.pi, N_vorfs)
X, Y = np.meshgrid(scalings, 2.*np.arange(1, max_r+1)-1.)
Z = np.arange(max_r*N_vorfs).reshape(X.shape)
fig, axs = plt.subplots(2, 1, gridspec_kw={'height_ratios': [3, 1]})
axs[0].contour(X, Y, Z)
print(tikzplotlib.get_tikz_code())
plt.show()
I get errors from tikzplotlib, namely
Traceback (most recent call last):
File ".../to_pgfplot.py", line 19, in <module>
print(tikzplotlib.get_tikz_code())
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 209, in get_tikz_code
data, content = _recurse(data, figure)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 353, in _recurse
data, children_content = _recurse(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 378, in _recurse
data, cont = _draw_collection(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 319, in _draw_collection
return _path.draw_pathcollection(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_path.py", line 214, in draw_pathcollection
p = obj.get_paths()[0]
IndexError: list index out of range

Related

Plot a function with telegram bot (python, matplotlib)

I faced with the problem during telegram bot writing. I would be very happy if somebody help me with this.
My code
import telebot
import matplotlib.pyplot as plt
import numpy as np
...
def plot_func(message):
x = np.linspace(-5,5,100)
y = message.text # <-- here is something wrong I supppose
plt.plot(x, y, 'r')
plt.savefig('plot_name.png', dpi = 300)
bot.send_photo(message.chat.id, photo=open('plot_name.png', 'rb'))
#plt.show()
Main idea
User send function, bot plot it and send image back:
ERROR
/home/anmnv/Desktop/news_scrapper_bot/bot.py:148: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail.
plt.plot(x, y, 'r')
Traceback (most recent call last):
File "/home/anmnv/Desktop/news_scrapper_bot/bot.py", line 424, in <module>
bot.polling(none_stop=True)
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1047, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1122, in __threaded_polling
raise e
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1078, in __threaded_polling
self.worker_pool.raise_exceptions()
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/util.py", line 154, in raise_exceptions
raise self.exception_info
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/util.py", line 98, in run
task(*args, **kwargs)
File "/home/anmnv/Desktop/news_scrapper_bot/bot.py", line 148, in plot_func
plt.plot(x, y, 'r')
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/pyplot.py", line 2730, in plot
return gca().plot(
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_axes.py", line 1662, in plot
lines = [*self._get_lines(*args, data=data, **kwargs)]
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 311, in __call__
yield from self._plot_args(
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 504, in _plot_args
raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (100,) and (1,)
Thank you in advance
Assuming message.text contains the string 'x**2', you can use numexpr.evaluate to convert to numpy array:
import numexpr
import matplotlib.pyplot as plt
x = np.linspace(-5, 5, 100)
y = numexpr.evaluate(message.text) # message.text = 'x**2'
plt.plot(x, y, 'r')
Output:

Buffer is too small for requested array-Astropy

I'm reading TESS data and as you might expect it can be really large, My Buffer is too small. Is there a way I can avoid this error? Like maybe skip the file that has a large file? Or is there a more permanent solution(not involving more memory)? My Code is below, along with the Full Error
from lightkurve import TessTargetPixelFile
import lightkurve as lk
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def func(tpf):
tpf.plot(aperture_mask=tpf.pipeline_mask);
lc = tpf.to_lightcurve()
mask = (lc.time.value < 1464)
masked_lc = lc[mask]
clipped_lc = masked_lc.remove_outliers(sigma=5);
flat_lc = clipped_lc.flatten()
binned_lc = flat_lc.bin(binsize=5)
periodogram = binned_lc.to_periodogram(method="bls", period=np.arange(1, 20, 0.001))
print(periodogram.plot())
planet_b_period = periodogram.period_at_max_power
planet_b_t0 = periodogram.transit_time_at_max_power
planet_b_dur = periodogram.duration_at_max_power
ax = binned_lc.fold(period=planet_b_period, epoch_time=planet_b_t0).scatter()
ax.set_xlim(-5, 5);
best_fit_period = periodogram.period_at_max_power
print('Best fit period: {:.3f}'.format(best_fit_period))
bfc=best_fit_period
print(bfc)
folded_lc = binned_lc.fold(period=bfc)
folded_lc.scatter(s=7);
plt.show()
planet_b_period
planet_b_model = periodogram.get_transit_model(period=planet_b_period,
transit_time=planet_b_t0,
duration=planet_b_dur)
ax = binned_lc.fold(planet_b_period, planet_b_t0).scatter(s=7)
planet_b_model.fold(planet_b_period, planet_b_t0).plot(ax=ax, c='r', lw=2)
ax.set_xlim(-5, 5);
dataset=pd.read_csv("all_targets_S001_v1.csv")
d=dataset["TICID"]
print(d)
IDs=[]
for i in range(len(d)):
IDs.append("TIC"+str(d[i]))
for i in range(len(IDs)):
tpf_file = lk.search_targetpixelfile(IDs[i], mission="TESS", sector=5).download(quality_bitmask='default')
try:
func(tpf_file)
continue
except:
continue
Thanks
The Full Error
WARNING: File may have been truncated: actual file length (262144) is smaller than the expected size (46402560) [astropy.io.fits.file]
Traceback (most recent call last):
File "lc.py", line 42, in <module>
tpf_file = lk.search_targetpixelfile(IDs[i], mission="TESS", sector=5).download(quality_bitmask='default')
File "C:\ProgramData\Anaconda3\lib\site-packages\lightkurve\utils.py", line 555, in wrapper
return f(*args, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\lightkurve\search.py", line 355, in download
return self._download_one(
File "C:\ProgramData\Anaconda3\lib\site-packages\lightkurve\search.py", line 290, in _download_one
return read(path, quality_bitmask=quality_bitmask, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\lightkurve\io\read.py", line 112, in read
return getattr(__import__("lightkurve"), filetype)(path_or_url, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\lightkurve\targetpixelfile.py", line 2727, in __init__
quality_array=self.hdu[1].data["QUALITY"], bitmask=quality_bitmask
File "C:\ProgramData\Anaconda3\lib\site-packages\astropy\utils\decorators.py", line 758, in __get__
val = self.fget(obj)
File "C:\ProgramData\Anaconda3\lib\site-packages\astropy\io\fits\hdu\table.py", line 399, in data
data = self._get_tbdata()
File "C:\ProgramData\Anaconda3\lib\site-packages\astropy\io\fits\hdu\table.py", line 171, in _get_tbdata
raw_data = self._get_raw_data(self._nrows, columns.dtype,
File "C:\ProgramData\Anaconda3\lib\site-packages\astropy\io\fits\hdu\base.py", line 520, in _get_raw_data
return self._file.readarray(offset=offset, dtype=code, shape=shape)
File "C:\ProgramData\Anaconda3\lib\site-packages\astropy\io\fits\file.py", line 330, in readarray
return np.ndarray(shape=shape, dtype=dtype, offset=offset,
TypeError: buffer is too small for requested array

error in plot graph using matlpotlib.pyplot module([ValueError: x and y must have same first dimension, but have shapes (2711, 4) and (678,)]

import pandas as pd
import quandl
import math
import numpy as np
from sklearn import preprocessing, model_selection,svm
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
quandl.ApiConfig.api_key = "FVeuw21FAe86ux3J3ePr"
df=quandl.get("WIKI/GOOGL")
df=df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume']]
df['HL_PCT']=(df['Adj. High']-df['Adj. Close'])/df['Adj. Close']*100
df['DL_PCT']=(df['Adj. Close']-df['Adj. Open'])/df['Adj. Open']*100
df=df[['Adj. Close','HL_PCT','DL_PCT','Adj. Volume']]
forcast_col='Adj. Close'
df.fillna(-9999,inplace=True)
forcast_out=int(math.ceil(0.01*len(df)))
print(forcast_out)
df['label']=df[forcast_col].shift(-forcast_out)
df.dropna(inplace=True)
X=np.array(df.drop(['label'],1))
y=np.array(df['label'])
X=preprocessing.scale(X)
y=np.array(df['label'])
print (len(X),len(y))
X.shape[0]!=y.shape[0]
X_train,X_text,y_test,y_train=train_test_split(X,y,test_size=0.2)
plt.xlabel('area(m^2)')
plt.ylabel('price(Rs)')
plt.plot(X_train,y_train,color='blue',marker='.')
plt.show()
reg=LinearRegression()
reg.fit(X_train,y_train)
accuracy=reg.score(X_test,y_test)
print(accuracy)
the error i got while running this code
Traceback (most recent call last):
File "c:/Users/user/Desktop/projetcs/machine learning/mc1.py", line 31, in <module>
plt.plot(X_train,y_train,color='blue',marker='.')
File "C:\Users\user\python11\lib\site-packages\matplotlib\pyplot.py", line 2824, in plot
return gca().plot(
File "C:\Users\user\python11\lib\site-packages\matplotlib\axes\_axes.py", line 1743, in plot
lines = [*self._get_lines(*args, data=data, **kwargs)]
File "C:\Users\user\python11\lib\site-packages\matplotlib\axes\_base.py", line 273, in __call__
yield from self._plot_args(this, kwargs)
File "C:\Users\user\python11\lib\site-packages\matplotlib\axes\_base.py", line 399, in _plot_args
raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension,

basemap.maskoceans: 'float' object cannot be interpreted as an integer

I'm getting the error:
TypeError: 'float' object cannot be interpreted as an integer
when I call maskoceans. Why is this? I'm running python3.
from mpl_toolkits.basemap import Basemap
from mpl_toolkits.basemap import maskoceans
from mpl_toolkits.basemap import interp
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
import numpy as np
places = {
(-8.91508040128176, 52.23826465): 0,
(-6.45854802816101, 52.64127685): 21,
(-9.03867527891856, 52.78809005): 0,
(-8.70926037608263, 53.717247): 0,
(-6.8217677, 54.3303964): 0,
(-6.1658125, 53.5255827): 4
}
m = Basemap(llcrnrlon=-10.56, llcrnrlat=51.39, urcrnrlon=-5.34, urcrnrlat=55.43,
lat_1=30., lat_2=60., lat_0=53.41, lon_0=-7.95,
resolution="i")
x, y, values = np.array([(x, y, v) for (x, y), v in places.items()]).T
coords = np.stack((x, y)).T
x, y = np.mgrid[-11:-4:10j, 51:56:10j]
z = griddata(coords, values, (x, y), method='nearest')
mdata = maskoceans(x, y, z, resolution = 'h', grid = 10, inlands=True)
plt.contour(x[:,0], x[0,:], mdata.T,linewidths=0.5,colors='k',z=99)
plt.contourf(x[:,0], y[0,:], mdata.T,cmap=plt.cm.Purples, z=100)
Here's the full stacktrack:
Traceback (most recent call last):
File "plot.py", line 28, in <module>
mdata = maskoceans(x, y, z, resolution = 'h', grid = 10, inlands=True)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mpl_toolkits/basemap/__init__.py", line 5107, in maskoceans
_readlsmask(lakes=inlands,resolution=resolution,grid=grid)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mpl_toolkits/basemap/__init__.py", line 5132, in _readlsmask
np.reshape(np.fromstring(lsmaskf.read(),dtype=np.uint8),(nlats,nlons))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 257, in reshape
return _wrapfunc(a, 'reshape', newshape, order=order)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 62, in _wrapfunc
return _wrapit(obj, method, *args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 42, in _wrapit
result = getattr(asarray(obj), method)(*args, **kwds)
TypeError: 'float' object cannot be interpreted as an integer
If you use Python3, you need to do a simple change to this file:
"your_python3_install_directory/lib/python3.x/site-packages/mpl_toolkits/basemap/init.py"
Between line 5125 and 5130, find "nlats = nlons/2" and change it to "nlats = nlons//2".
This should solve the problem.

Matplotlib ArtistAnimation gives TypeError: 'AxesImage' object is not iterable [duplicate]

This question already has answers here:
matplotlib imshow(): how to animate?
(2 answers)
Closed 6 years ago.
Can you please help me figuring out what the problem is here? I don't know what is going wrong. Single plots from img can be plotted just fine, but the animation module gives an error. The Traceback says:
Traceback (most recent call last):
File "/home/ckropla/workspace/TAMM/Sandkasten.py", line 33, in <module>
ani = animation.ArtistAnimation(fig, img, interval=20, blit=True,repeat_delay=0)
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 818, in __init__
TimedAnimation.__init__(self, fig, *args, **kwargs)
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 762, in __init__
*args, **kwargs)
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 481, in __init__
self._init_draw()
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 824, in _init_draw
for artist in f:
TypeError: 'AxesImage' object is not iterable
Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def FUNCTION(p,r,t):
k_0,dx,c = p
x,y = r
z = np.exp(1j*(k_0[0]*np.meshgrid(x,y)[0]+k_0[1]*np.meshgrid(x,y)[1]-c*t))*np.exp(-((np.sqrt(np.meshgrid(x,y)[0]**2+np.meshgrid(x,y)[1]**2)-c*t)/(2*dx))**2 )*(2/np.pi/dx**2)**(1/4)
z = abs(z)
#k,F = FFT((x-c*t),y)
return(x,y,z)
#Parameter
N = 500
n = 20
x = np.linspace(-10,10,N)
y = np.linspace(-10,10,N)
t = np.linspace(0,30,n)
r=[x,y]
k_0 = [1,1]
dx = 1
c = 1
p = [k_0,dx,c]
fig = plt.figure("Moving Wavepackage")
Z = []
img = []
for i in range(n):
Z.append(FUNCTION(p,r,t[i])[2])
img.append(plt.imshow(Z[i]))
ani = animation.ArtistAnimation(fig, img, interval=20, blit=True,repeat_delay=0)
plt.show()
Each element in img needs to be a sequence of artists, not a single artist. If you change img.append(plt.imshow(Z[i])) to img.append([plt.imshow(Z[i])]) then your code works fine.

Categories

Resources