why is plt.show() not working. File name report.py - python

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?

Related

UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail

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

Python script throws ValueError while plotting data

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.

Pyinstaller creating exe file without pandas but still requires pandas import

I have a python code which runs fine when I run it through the cmd using python filename.py
But when I create exe file using pyinstaller the exe file opens and prints an exception I made(see at the bottom of the code) says no module name pandas.
Then, If I edit the code and import pandas and recreate the exe file it will work.
Does anyone have an idea?
I'm not using pandas in the code, and even PyCharm marks the import pandas line as redundant.
I have Windows 10 and anaconda installed.
Thank you
import csv,re
import os.path, time, datetime
import subprocess
import sys
try:
nameOfTitle= "name"
SName="S"
os.chdir(r'someaddress')
summaries_csv_path="summaries.csv"
HtmlPath='html/-----.htm'
HtmlPathNoDir='-----.htm'
HtmlPathNoDirC='----.htm'
HtmlPathNoDir='-----.htm'
sub="name"
headerH3="------"
dataWlCsv="raw.zip"
opRow = 0
sumRow = 0
col_num=0
innerCount=0
x = 0
headerList = list()
htmlfile = open(HtmlPath,"w")
execfile(r'some address')#header
readOp = csv.reader(open(r'some address.csv'),delimiter=',')
for row in readOp: # Read a single row from the CSV file
execfile(r'\some address.py')#logic
execfile(r'some address.py')#footer
except:
e = sys.exc_info()[1]
print("<p>Error: %s</p>" % e)
print "IN "+" MODUL!"

how to set up a custom font with custom path to matplotlib global font?

There is a custom font in my app
app_path='/home/user1/myapp'
fname='/home/user1/myapp/font/myfont.ttf'
To setup globlal font to matplotlib,the docs said like this:
plt.rcParams['font.sans-serif']=['xxx font']
But it only works when the font already in system font path,and I have to use my custom font in my app path '/home/user1/myapp/font/myfont.ttf'
I know there is a way like this:
fname='/home/user1/myapp/font/myfont.ttf'
myfont=fm.FontProperties(fname=fname)
ax1.set_title('title test',fontproperties=myfont)
But that is not what I want,I don't want to set 'fontproperties' all the time,because there are some much code to change
Solved the problem like this:
import matplotlib.font_manager as font_manager
font_dirs = ['/my/custom/font/dir', ]
font_files = font_manager.findSystemFonts(fontpaths=font_dirs)
font_list = font_manager.createFontList(font_files)
font_manager.fontManager.ttflist.extend(font_list)
mpl.rcParams['font.family'] = 'My Custom Font'
The fontpaths kwarg can also be a string in case you only have a single directory to import from.
2021 Update
I came across this issue recently and found this the most simple way to deal with it.
Adding the font is the important part, otherwise, the font will not be detected:
import matplotlib.pyplot as plt
from matplotlib import font_manager
font_path = 'Inter-Regular.otf' # Your font path goes here
font_manager.fontManager.addfont(font_path)
prop = font_manager.FontProperties(fname=font_path)
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = prop.get_name()
For newer matplotlib module (e.g. version >=3.2)
createFontList is deprecated.
Hoever, you can make a font entry with ttf file path and custom name,
then add it to fontManager.ttflist, and assign matplotlib.rcParams['font.familt'] to that name.
Now you can start to make a plot without 'fontproperties' etc.
import matplotlib as mpl
import matplotlib.font_manager as fm
fe = fm.FontEntry(
fname='your custom ttf file path',
name='your custom ttf font name')
fm.fontManager.ttflist.insert(0, fe) # or append is fine
mpl.rcParams['font.family'] = fe.name # = 'your custom ttf font name'

Python script for Blender failed

In Blender 2.62 I was using this script to display a point:
import bpy
from bpy.props import FloatVectorProperty, IntProperty, FloatProperty
from add_utils import AddObjectHelper, add_object_data
data0=[]
data0.append((float(69.3456), float(36.4562), float(26.8232)))
me0 = bpy.data.meshes.new( name = "point cloud0")
me0.from_pydata( data0, [], [] )
me0.update()
add_object_data(bpy.context, me0, [])
After having updated to Blender 2.67a the execution returns a failure and the following error is reported in the console window:
ImportError: No module named 'add_utils'
Do you have any clue why this should not work anymore?
Thank you :)
Add the missing bpy_extras import at the start of the script
import bpy
import bpy_extras
from bpy.props import FloatVectorProperty, IntProperty, FloatProperty
from bpy_extras import object_utils.object_data_add
from bpy_extras import AddObjectHelper
The API for add_object_data appears to have changed to object_data_add so you'll need to change that in the script too.
object_data_add(bpy.context, me0, [])

Categories

Resources