I have tried an example from the page 11 of tephigramDocs, but it raises a ValueError. The code is the following:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os.path
import tephi
dew_point = os.path.join(tephi.DATA_DIR, ’dews.txt’)
dew_data = tephi.loadtxt(dew_point, column_titles=(’pressure’, ’dewpoint’))
dews = zip(dew_data.pressure, dew_data.dewpoint)
tpg = tephi.Tephigram()
tpg.plot(dews)
plt.show()
Clearly the format of data passed to the plot function is wrong but I cannot find a solution for this. The error message is:
ValueError: The environment profile data requires to be a sequence of pressure, temperature value pairs.
Related
I am trying to return the data list and plot. They do display in the HTML code instead of web page. When I look at the terminal it shows "UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail."
from io import BytesIO
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
def extract(request):
if request.method == 'POST':
if request.FILES.get('document'):
file = request.FILES['document']
if 'data' in request.POST:
data = df = pd.read_excel(file)
mpl.rcParams['agg.path.chunksize'] = 10000
plt.plot(data["time"], data["make"], label='male')
plt.plot(data["time"], data["female"], label='female')
plt.xlabel('T')
plt.ylabel('M and F')
plt.legend()
buffer = BytesIO()
plt.savefig(buffer, format='png')
buffer.seek(0)
image_png = buffer.getvalue()
buffer.close()
graphic = base64.b64encode(image_png)
graphic = graphic.decode('utf-8')
dic_result = {'graphic': graphic}
dataa = []
for index in range(len(data["make"])):
data.append(tuple(dataa["male"][index], dataa["female"][index]))
return render(request, 'bothdata.html', {'data': dataa}, dic_result)
return render(request, 'extract.html')
It's just warning, it will run but can be a really painful problem. I'm not exactly an expert but I'm having the same warning, and it can be worse if you try to use matplotlib in a Thread besides Main Thread. For some reason matplotlib don't work well on Threads, which can cause your aplication to crash.
try this, it worked for me
import matplotlib
matplotlib.use('agg')
Agg, is a non-interactive backend that can only write to files.
For more information and other ways of solving it see https://matplotlib.org/stable/users/explain/backends.html
When I open the folder through windows powershell it works, but through ubuntu it doesn't work
import matplotlib.pyplot as plt
import psycopg2
import os
import sys
cur.execute(f"SELECT date as date, revenue_rates_usd ->> '{desired_currency}' AS {desired_currency} FROM usd_rates WHERE date BETWEEN '{start_date}' AND '{end_date}';", conn)
dates = []
values = []
for row in cur.fetchall():
# print(row[1])
dates.append(row[0])
values.append(row[1])
plt.plot_date(dates, values, "-")
plt.title(f'Exchange from USD to {desired_currency}')
plt.show()
That is how I run it:
/mnt/c/Users/owner/Desktop/Tamatem/.venv/bin/python /mnt/c/Users/owner/Desktop/Tamatem/report.py JOD 2021-07-1 2021-07-22
And when I run it, there is no any errors.
You might have to change the "backend".
import matplotlib
matplotlib.use('Agg')
Do you call the show() method inside a terminal or application that has access to a graphical environment?
Also try to use other GUI backends (TkAgg, wxAgg, Qt5Agg, Qt4Agg).
Further information how this can be done here:How can I set the 'backend' in matplotlib in Python?
My code is the following, it used to run perfectly for quite a while but suddenly got the error message. Tried other stocks data providers like Google & alpha vantage and got the same error message.
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime
import numpy as np
!pip install ffn
import ffn
import pandas_datareader.data as web
from pandas.plotting import register_matplotlib_converters
from pylab import *
import pandas as pd
import pandas_profiling
import matplotlib.pyplot as plot
from matplotlib import style
%matplotlib inline
stocks = 'alf,mrin,auud,sncr,ddd,ssnt,seac,ttd'
df = ffn.get(stocks, start='06/18/2021').to_returns().dropna()
print(df.as_format('.2%'))
df = df.apply(pd.to_numeric, errors='coerce').fillna(0)
sums = df.select_dtypes(np.number).sum()
sort_sums = sums.sort_values(ascending = False)
pd.set_option('Display.max_rows', len(stocks))
sharpe = ffn.core.calc_sharpe(df)
sharpe = sharpe.sort_values(ascending = False)
df.append({stocks: sharpe},ignore_index=True)
print(str(sort_sums.as_format('.2%')))
print(sharpe.head(10))
df.shape
I'm using Google Colaboratory
Please run the code and you will see the Error message I'm getting (I can't copy it to here).
Please help & thank you very much in advance!
I have a problem with matplotlib in Pycharm.my code is:
import matplotlib.pyplot as plt
import numpy as np
T = np.linspace(10,100,10)
es = 611*np.exp(17.27*T/(237.3+T))
plt.plot(T,es)
plt.xlabel('T (degree Celcius)')
plt.ylabel('es (pa)')
plt.show()
and after i ran this code,Pycharm showed this error:
enter link description here
what should i do to solve it??
In my master file I have:
import matplotlib.pyplot as plt
import seaborn
import numpy as np
import time
import sys
sys.path.append("C:/.../python check/createsplit")
import createsplit
data='MJexample'
X,Y,N,Ntr=create_training_data(data)
where I am calling create_training_data function from createsplit.py file which is:
import numpy as np
import scipy.io
def create_training_data(data_type):
"""
creates training data
"""
if data_type=='MJexample':
N=300
Ntr = 150
X=np.linspace(0,1,N)
X = np.array([X,X*X,np.linspace(5,10,N),np.sin(X),np.cos(X),np.sin(X)*np.cos(X)]).T
fac=40
Y=np.array([np.sin(fac*x)*np.cos(fac*x**2) for x in X[:,0]])[:,None]
_X=X
_Y=Y
return _X,_Y,N,Ntr
However running my original file results in error: NameError: global name 'np' is not defined for some reason I do not understand. I assume I am importing the functions in a wrong way but I don't really understand what would be wrong.
I think this issue raises just because of a wrong call of the function. Try
X, Y, N, Ntr = createsplit.create_training_data(data)
instead, and it should work.