Cannot load backend 'Qt5Agg' or it doesn't show any plot - python-3.x

I'm trying to use 'Qt5Agg' matplotlib backend in Jupyter , but when I run %matplotlib qt, i get the following error:
ImportError Traceback (most recent call last)
<ipython-input-1-f6a92ad1c7f8> in <module>
----> 1 get_ipython().run_line_magic('matplotlib', 'qt')
2 import numpy as np
3 from scipy.integrate import odeint
4 import matplotlib.pyplot as plt
5 from mpl_toolkits.mplot3d import Axes3D
~/.local/lib/python3.5/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
2312 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2313 with self.builtin_trap:
-> 2314 result = fn(*args, **kwargs)
2315 return result
2316
</home/cs/.local/lib/python3.5/site-packages/decorator.py:decorator-gen-108> in matplotlib(self, line)
~/.local/lib/python3.5/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
~/.local/lib/python3.5/site-packages/IPython/core/magics/pylab.py in matplotlib(self, line)
97 print("Available matplotlib backends: %s" % backends_list)
98 else:
---> 99 gui, backend = self.shell.enable_matplotlib(args.gui.lower() if isinstance(args.gui, str) else args.gui)
100 self._show_matplotlib_backend(args.gui, backend)
101
~/.local/lib/python3.5/site-packages/IPython/core/interactiveshell.py in enable_matplotlib(self, gui)
3412 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3413
-> 3414 pt.activate_matplotlib(backend)
3415 pt.configure_inline_support(self, backend)
3416
~/.local/lib/python3.5/site-packages/IPython/core/pylabtools.py in activate_matplotlib(backend)
312
313 import matplotlib.pyplot
--> 314 matplotlib.pyplot.switch_backend(backend)
315
316 # This must be imported last in the matplotlib series, after
~/.local/lib/python3.5/site-packages/matplotlib/pyplot.py in switch_backend(newbackend)
220 "Cannot load backend {!r} which requires the {!r} interactive "
221 "framework, as {!r} is currently running".format(
--> 222 newbackend, required_framework, current_framework))
223
224 rcParams['backend'] = rcParamsDefault['backend'] = newbackend
ImportError: Cannot load backend 'Qt5Agg' which requires the 'qt5' interactive framework, as 'headless' is currently running
I tried running first:
import matplotlib
matplotlib.use('Qt5Agg')
but if i run again %matplotlib qt, i'm getting the same error.
If i don't run the magic command, and i plot something, it doesn't show anything.

Related

TypeError: string indices must be integers in the time of downloading stock data

Previously, this same code was running perfectly. However, I encountered this error recently "TypeError: string indices must be integers".
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pandas_datareader.data as web
import datetime
start=datetime.datetime(2015,6,1)
end=datetime.datetime(2022,6,30)
sbin=web.DataReader('SBIN.BO','yahoo',start,end)
tatamotors=web.DataReader('TATAMOTORS.BO','yahoo',start,end)
reliance=web.DataReader('RELIANCE.BO','yahoo',start,end)
I have tried this code by considering other stock aslo. But same result obtained. After running the above code, the error occured as follows:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [3], in <cell line: 1>()
----> 1 sbin=web.DataReader('SBIN.BO','yahoo',start,end)
2 tatamotors=web.DataReader('TATAMOTORS.BO','yahoo',start,end)
3 reliance=web.DataReader('RELIANCE.BO','yahoo',start,end)
File C:\ProgramData\Anaconda3\lib\site-packages\pandas\util\_decorators.py:207, in deprecate_kwarg.<locals>._deprecate_kwarg.<locals>.wrapper(*args, **kwargs)
205 else:
206 kwargs[new_arg_name] = new_arg_value
--> 207 return func(*args, **kwargs)
File C:\ProgramData\Anaconda3\lib\site-packages\pandas_datareader\data.py:370, in DataReader(name, data_source, start, end, retry_count, pause, session, api_key)
367 raise NotImplementedError(msg)
369 if data_source == "yahoo":
--> 370 return YahooDailyReader(
371 symbols=name,
372 start=start,
373 end=end,
374 adjust_price=False,
375 chunksize=25,
376 retry_count=retry_count,
377 pause=pause,
378 session=session,
379 ).read()
381 elif data_source == "iex":
382 return IEXDailyReader(
383 symbols=name,
384 start=start,
(...)
390 session=session,
391 ).read()
File C:\ProgramData\Anaconda3\lib\site-packages\pandas_datareader\base.py:253, in _DailyBaseReader.read(self)
251 # If a single symbol, (e.g., 'GOOG')
252 if isinstance(self.symbols, (string_types, int)):
--> 253 df = self._read_one_data(self.url, params=self._get_params(self.symbols))
254 # Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT'])
255 elif isinstance(self.symbols, DataFrame):
File C:\ProgramData\Anaconda3\lib\site-packages\pandas_datareader\yahoo\daily.py:153, in YahooDailyReader._read_one_data(self, url, params)
151 try:
152 j = json.loads(re.search(ptrn, resp.text, re.DOTALL).group(1))
--> 153 data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
154 except KeyError:
155 msg = "No data fetched for symbol {} using {}"
TypeError: string indices must be integers.
Please help me in solving this issue.
There is a long-standing gh-issue that discusses your problem. As the corresponding PR hasn't been merged as of today, I would recommend to use the yfinance override instead:
import datetime
import pandas_datareader.data as web
import yfinance as yf
yf.pdr_override()
start=datetime.datetime(2015, 6, 1)
end=datetime.datetime(2022, 6, 30)
sbin = web.DataReader('SBIN.BO', start, end)
tatamotors = web.DataReader('TATAMOTORS.BO', start, end)
reliance = web.DataReader('RELIANCE.BO', start, end)
Output for SBIN:
Open High Low Close Adj Close Volume
Date
2015-06-01 00:00:00+05:30 279.000000 281.950012 277.600006 278.149994 265.453278 1331528
2015-06-02 00:00:00+05:30 278.500000 279.500000 265.500000 266.250000 254.096466 3382530
2015-06-03 00:00:00+05:30 267.149994 268.000000 255.100006 257.549988 245.793579 2706069

Plotly is not working module 'tenacity' has no attribute 'retry'

I am trying to produce a simple scatter plot using Plotly
And all the time I am getting this error:
module 'tenacity' has no attribute 'retry'
I searched for solutions but nothing worked.
In particular, I have tried the following:
Uninstall and install again plotly
Upgrade pip and then upgrade plotly
install tenacity into my environment
Can someone help?
Here is the python script I am using:
import plotly.express as px
fig = px.scatter(df_performance, x="ytd", y="cagr",
size ='Market Cap', template='plotly_dark',
color_continuous_scale=px.colors.sequential.Viridis, title = 'S&P 500 Companies Perfomance the Last 4 months')
fig.show()
where df_performance is just a pandas dataframe with three columns (ytd,cagr, Market Cap)
My python version is: 3.8.12
Update: Here is the full trace
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/var/folders/7g/gr9fl0cx43g5f42xf78n_str0000gn/T/ipykernel_28716/3796243394.py in <module>
2 size ='Market Cap', template='plotly_dark',
3 color_continuous_scale=px.colors.sequential.Viridis, title = 'S&P 500 Companies Perfomance the Last 4 months')
----> 4 fig.show()
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/site-packages/plotly/basedatatypes.py in show(self, *args, **kwargs)
3396 import plotly.io as pio
3397
-> 3398 return pio.show(self, *args, **kwargs)
3399
3400 def to_json(self, *args, **kwargs):
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/site-packages/_plotly_utils/importers.py in __getattr__(import_name)
34 rel_module = ".".join(rel_path_parts[:-1])
35 class_name = import_name
---> 36 class_module = importlib.import_module(rel_module, parent_name)
37 return getattr(class_module, class_name)
38
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/importlib/__init__.py in import_module(name, package)
125 break
126 level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)
128
129
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/importlib/_bootstrap.py in _gcd_import(name, package, level)
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/importlib/_bootstrap.py in _find_and_load(name, import_)
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/importlib/_bootstrap.py in _load_unlocked(spec)
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/importlib/_bootstrap_external.py in exec_module(self, module)
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/site-packages/plotly/io/_renderers.py in <module>
10 from plotly import optional_imports
11
---> 12 from plotly.io._base_renderers import (
13 MimetypeRenderer,
14 ExternalRenderer,
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/site-packages/plotly/io/_base_renderers.py in <module>
10 from plotly import utils, optional_imports
11 from plotly.io import to_json, to_image, write_image, write_html
---> 12 from plotly.io._orca import ensure_server
13 from plotly.io._utils import plotly_cdn_url
14 from plotly.offline.offline import _get_jconfig, get_plotlyjs
~/opt/anaconda3/envs/Spyder_env/lib/python3.8/site-packages/plotly/io/_orca.py in <module>
1453
1454
-> 1455 #tenacity.retry(
1456 wait=tenacity.wait_random(min=5, max=10), stop=tenacity.stop_after_delay(60000),
1457 )
AttributeError: module 'tenacity' has no attribute 'retry'
you have described the data so synthesized it
used exactly your code, runs without issues. plotly 5.5.0
import plotly.express as px
import pandas as pd
import numpy as np
df_performance = pd.DataFrame(
{
"ytd": pd.date_range("1-jan-2021", freq="B", periods=100),
"cagr": np.linspace(2, 5, 100) * np.random.uniform(.7,1,100),
"Market Cap": np.linspace(5,20, 100) * np.random.uniform(.7,1,100),
}
)
fig = px.scatter(
df_performance,
x="ytd",
y="cagr",
size="Market Cap",
template="plotly_dark",
color_continuous_scale=px.colors.sequential.Viridis,
title="S&P 500 Companies Perfomance the Last 4 months",
)
fig

import matplotlib.pyplot as plt - KeyError: 'keymap.quit_all'

import matplotlib.pyplot as plt
When I enter the code above, I get the following error
#( conda install matplotlib/ python 3.5.2/ anaconda 3.4.2 / window10)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-19-eff513f636fd> in <module>()
----> 1 import matplotlib.pyplot as plt
C:\Users\kimjimin\Anaconda3\lib\site-packages\matplotlib\pyplot.py in <module>()
36 from matplotlib.cbook import deprecated, warn_deprecated
37 from matplotlib import docstring
---> 38 from matplotlib.backend_bases import FigureCanvasBase
39 from matplotlib.figure import Figure, figaspect
40 from matplotlib.gridspec import GridSpec
C:\Users\kimjimin\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in <module>()
51 import numpy as np
52
---> 53 from matplotlib import (
54 backend_tools as tools, cbook, colors, textpath, tight_bbox, transforms,
55 widgets, get_backend, is_interactive, rcParams)
C:\Users\kimjimin\Anaconda3\lib\site-packages\matplotlib\backend_tools.py in <module>()
389
390
--> 391 class ToolQuitAll(ToolBase):
392 """Tool to call the figure manager destroy method"""
393
C:\Users\kimjimin\Anaconda3\lib\site-packages\matplotlib\backend_tools.py in ToolQuitAll()
393
394 description = 'Quit all figures'
--> 395 default_keymap = rcParams['keymap.quit_all']
396
397 def trigger(self, sender, event, data=None):
C:\Users\kimjimin\Anaconda3\lib\site-packages\matplotlib\__init__.py in __getitem__(self, key)
904 val = alt_val(val)
905 elif key in _deprecated_set and val is not None:
--> 906 if key.startswith('backend'):
907 warnings.warn(self.msg_backend_obsolete.format(key),
908 mplDeprecation)
KeyError: 'keymap.quit_all'

ModuleNotFoundError: No module named 'autoreload'

I run the following code from convolutional neural network tutorials on jupyter notebook with python 3 kernel, and got the ModuleNotFoundError: No module named 'autoreload';
import numpy as np
import h5py
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
%load_ext autoreload
%autoreload 2
np.random.seed(1)
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-3d0ea63c7843> in <module>()
8 plt.rcParams['image.cmap'] = 'gray'
9
---> 10 get_ipython().magic('load_ext autoreload # reload modules before executing user code')
11 get_ipython().magic('autoreload 2 # Reload all modules (except those excluded by %aimport)')
12
/opt/conda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
2156 magic_name, _, magic_arg_s = arg_s.partition(' ')
2157 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2158 return self.run_line_magic(magic_name, magic_arg_s)
2159
2160 #-------------------------------------------------------------------------
/opt/conda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
2077 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2078 with self.builtin_trap:
-> 2079 result = fn(*args,**kwargs)
2080 return result
2081
<decorator-gen-62> in load_ext(self, module_str)
/opt/conda/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
186 # but it's overkill for just that one bit of state.
187 def magic_deco(arg):
--> 188 call = lambda f, *a, **k: f(*a, **k)
189
190 if callable(arg):
/opt/conda/lib/python3.6/site-packages/IPython/core/magics/extension.py in load_ext(self, module_str)
35 if not module_str:
36 raise UsageError('Missing module name.')
---> 37 res = self.shell.extension_manager.load_extension(module_str)
38
39 if res == 'already loaded':
/opt/conda/lib/python3.6/site-packages/IPython/core/extensions.py in load_extension(self, module_str)
81 if module_str not in sys.modules:
82 with prepended_to_syspath(self.ipython_extension_dir):
---> 83 __import__(module_str)
84 mod = sys.modules[module_str]
85 if self._call_load_ipython_extension(mod):
ModuleNotFoundError: No module named 'autoreload'
I just couldn't find any solution on this issue. How should I fix this error?
The module autoreload belongs to the library IPython, which is running in the background on Jupyter.
The same error occurred to me and it was due to a blank space, see:
.
So make sure that there are no spaces at the end of the command!
I hit this same error because I had a comment after the magic command:
bad:
%load_ext autoreload # this comment should be removed
good:
%load_ext autoreload

sklearn import error. No module named winreg on ubuntu 14.04

When I try to import a module from sklearn a receive an error:
In [1]: import sklearn
In [2]: from sklearn.linear_model import Lasso
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-2-b932cb9c16f8> in <module>()
----> 1 from sklearn.linear_model import Lasso
/usr/local/lib/python3.4/dist-packages/sklearn/linear_model/__init__.py in <module>()
10 # complete documentation.
11
---> 12 from .base import LinearRegression
13
14 from .bayes import BayesianRidge, ARDRegression
/usr/local/lib/python3.4/dist-packages/sklearn/linear_model/base.py in <module>()
26 from ..externals.joblib import Parallel, delayed
27 from ..base import BaseEstimator, ClassifierMixin, RegressorMixin
---> 28 from ..utils import as_float_array, atleast2d_or_csr, safe_asarray
29 from ..utils.extmath import safe_sparse_dot
30 from ..utils.sparsefuncs import mean_variance_axis0, inplace_column_scale
/usr/local/lib/python3.4/dist-packages/sklearn/utils/__init__.py in <module>()
9
10 from .murmurhash import murmurhash3_32
---> 11 from .validation import (as_float_array, check_arrays, safe_asarray,
12 assert_all_finite, array2d, atleast2d_or_csc,
13 atleast2d_or_csr, warn_if_not_float,
/usr/local/lib/python3.4/dist-packages/sklearn/utils/validation.py in <module>()
15
16 from ..externals import six
---> 17 from .fixes import safe_copy
18
19
/usr/local/lib/python3.4/dist-packages/sklearn/utils/fixes.py in <module>()
103
104 try:
--> 105 with ignore_warnings():
106 # Don't raise the numpy deprecation warnings that appear in
107 # 1.9
/usr/local/lib/python3.4/dist-packages/sklearn/utils/testing.py in __enter__(self)
297
298 def __enter__(self):
--> 299 clean_warning_registry() # be safe and not propagate state + chaos
300 warnings.simplefilter('always')
301 if self._entered:
/usr/local/lib/python3.4/dist-packages/sklearn/utils/testing.py in clean_warning_registry()
582 reg = "__warningregistry__"
583 for mod in sys.modules.copy().values():
--> 584 if hasattr(mod, reg):
585 getattr(mod, reg).clear()
586
/usr/lib/python3/dist-packages/scipy/lib/six.py in __getattr__(self, attr)
114 if attr in ("__file__", "__name__") and self.mod not in sys.modules:
115 raise AttributeError
--> 116 _module = self._resolve()
117 value = getattr(_module, attr)
118 setattr(self, attr, value)
/usr/lib/python3/dist-packages/scipy/lib/six.py in _resolve(self)
103
104 def _resolve(self):
--> 105 return _import_module(self.mod)
106
107 def __getattr__(self, attr):
/usr/lib/python3/dist-packages/scipy/lib/six.py in _import_module(name)
74 def _import_module(name):
75 """Import module, returning the module after the last dot."""
---> 76 __import__(name)
77 return sys.modules[name]
78
ImportError: No module named 'winreg'
In [3]:
I have installed sklearn with the command pip3 as explained in the official documentation
In [3]: sklearn.__version__
Out[3]: '0.15.1'
winreg should be a module available only for windows... how can I solve this?
EDIT:
This is the command that I have used to install sklearn :
sudo pip3 install -U scikit-learn
I have solved removing sklearn and installing the git version as explained here
https://askubuntu.com/questions/449326/installation-error-in-sklearn-for-python3

Resources