networkx draw graph deprecated message - python-3.x

I am trying to draw a graph networkx using python 3.6 with Jupyter notebook and the network package with anaconda. But the graph is not drawing per the documentation, I am just getting a deprecated message.
CODE:
import networkx as nx
import csv
import matplotlib as plt
G = nx.read_pajek('Hi-tech.net')
nx.draw(G)
MESSAGE:
MatplotlibDeprecationWarning: pyplot.hold is deprecated.
Future behavior will be consistent with the long-time default:
plot commands add elements without first clearing the
Axes and/or Figure.
b = plt.ishold()
Future behavior will be consistent with the long-time default:
plot commands add elements without first clearing the
Axes and/or Figure.
plt.hold(b)
warnings.warn("axes.hold is deprecated, will be removed in 3.0")

To avoid this warning, I just simply replace
nx.draw(G)
by
nx.draw_networkx(G)
My Python is 3.4, Jupyter '1.0.0' and networkx '1.11'.

I was able to get rid of the message by going into the networkx library and simply placing # in front of the lines which produced the error.
I would infer the .hold() function is no longer necessary, nor does it need ot be replaced

I could get nx.draw(G) to work by adding the following line of command:
%matplotlib inline

As error suggest ... I change nx_pylab.py at 611
# if cb.is_numlike(alpha):
if isinstance(alpha,numbers.Number):

I just commented out the line 365 of file __init__.py in Lib\site-packages\matplotlib\cbook which reads
#deprecated('3.0', 'isinstance(..., numbers.Number)')

Related

backtesting.py ploting function not working

I'm trying to learn backtesting.py, when I run the following sample code, it pops up these errors, anyone could help? I tried to uninstall the Bokeh package and reinstall an older version, but it doen't work.
BokehDeprecationWarning: Passing lists of formats for DatetimeTickFormatter scales was deprecated in Bokeh 3.0. Configure a single string format for each scale
C:\Users\paul_\AppData\Local\Programs\Python\Python310\lib\site-packages\bokeh\models\formatters.py:399: UserWarning: DatetimeFormatter scales now only accept a single format. Using the first prodvided: '%d %b'
warnings.warn(f"DatetimeFormatter scales now only accept a single format. Using the first prodvided: {fmt[0]!r} ")
BokehDeprecationWarning: Passing lists of formats for DatetimeTickFormatter scales was deprecated in Bokeh 3.0. Configure a single string format for each scale
C:\Users\paul_\AppData\Local\Programs\Python\Python310\lib\site-packages\bokeh\models\formatters.py:399: UserWarning: DatetimeFormatter scales now only accept a single format. Using the first prodvided: '%m/%Y'
warnings.warn(f"DatetimeFormatter scales now only accept a single format. Using the first prodvided: {fmt[0]!r} ")
GridPlot(id='p11925', ...)
import bokeh
import datetime
import pandas_ta as ta
import pandas as pd
from backtesting import Backtest
from backtesting import Strategy
from backtesting.lib import crossover
from backtesting.test import GOOG
class RsiOscillator(Strategy):
upper_bound = 70
lower_bound = 30
rsi_window = 14
# Do as much initial computation as possible
def init(self):
self.rsi = self.I(ta.rsi, pd.Series(self.data.Close), self.rsi_window)
# Step through bars one by one
# Note that multiple buys are a thing here
def next(self):
if crossover(self.rsi, self.upper_bound):
self.position.close()
elif crossover(self.lower_bound, self.rsi):
self.buy()
bt = Backtest(GOOG, RsiOscillator, cash=10_000, commission=.002)
stats = bt.run()
bt.plot()
An issue was opened for this in the GitHub repo:
https://github.com/kernc/backtesting.py/issues/803
A comment in the issue suggests to downgrade bokeh to 2.4.3:
python3 -m pip install bokeh==2.4.3
This worked for me.
I had a similar issue, using Spyder IDE.
Found out I need to call the below for the plot to show for Spyder.
backtesting.set_bokeh_output(notebook=False)
I have update Python to version 3.11 & downgrade bokeh to 2.4.3
This worked for me.
Downgrading Bokeh didn't work for me.
But, after importing backtesting in Jupyter, I needed to do:
backtesting.set_bokeh_output(notebook=False)
The expected plot was then generated in a new interactive browser tab.

Importing sympy and matplotlib.pyplot causes a deprecation warning

This runs fine without any warnings or errors,
from matplotlib import pyplot as plt
plt.plot(range(10))
This,
from matplotlib import pyplot as plt
import sympy
plt.plot(range(10))
Produces,
/home/username/.local/lib/python3.8/site-packages/matplotlib/backends/backend_gtk3.py:327:
DeprecationWarning: Gtk.Window.set_wmclass is deprecated
self.window.set_wmclass("matplotlib", "Matplotlib")
Note that if you import them both but don't call the plot function, you don't get the deprecation warning.
I have no idea what is going on. Googling that warning does not quite find anything related to Sympy. Python is at 3.8.5, Sympy at 1.8 and Matplotlib at 3.4.0.
The message you received is a warning and not an error. The difference being that your code has been executed normally, the message provides extra information that in some point in the future Gtk.Window.set_wmclass will not be available, it's a note to programmers (in this case the matplotlib devs) that they should change their code to use the new way of doing something. If you use a combination of old/new packages you should expect to see these warnings.
You can either ignore/suppress this warning message, or update your packages.
It's recommended that you use a virtual environment to isolate the Python that you use to from the Python that your system uses. It will allow you to use up-to-date versions of packages and you will no longer risk accidentally breaking system utilities. There are many options and since Python ~3.6 there's the venv module included in the standard library.

matplotlib.pyplot plot_date function breaks on cftime.datetime objects

Trying to plot data using the matplotlib.pyplot.plot_date function with datetime objects originating from the netCDF4.num2date function I get the following error:
In [1]: from netCDF4 import num2date
In [2]: from matplotlib.pyplot import plot_date
In [3]: d=num2date((86400,2*86400),"seconds since 2000-01-01")
In [4]: gca().plot_date(d,(0,1))
...
AttributeError: 'cftime._cftime.DatetimeGregorian' object has no attribute 'toordinal'
The above exception was the direct cause of the following exception:
ConversionError
...
ConversionError: Failed to convert value(s) to axis units: array([cftime.DatetimeGregorian(2000-01-02 00:00:00),
cftime.DatetimeGregorian(2000-01-03 00:00:00)], dtype=object)
The following package versions are installed:
pandas 1.0.3
matplotlib 3.2.1
netcdf4 1.5.1.2
cftime 1.1.1.2
As the same thing perfectly works on a different machine with older package versions, I assume a version issue.
Also, I've tried the solution suggested in this thread and other related threads which seemed like a similar issue, but
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
didn't help neither.
Any suggestions welcome;)
Found the answer myself, from version 1.1.0 the num2date function in the cftime package changed its default behaviour to return cftime datetime instances instead of python datetime instances where possible (the option argument only_use_cftime_datetimes is now True by default, instead of False). The plot_date function however, at least currently, doesn't handle these.
To avoid the issue, use the arguments only_use_cftime_dateimes=False and only_use_python_datetime=True or use the convenience function num2pydate.

Why will Seaborn function 'regplot' not run in Jupyter?

I am having trouble with code Seaborn regplot function in Jupyter notebooks using Watson-Studio.
Using Python 3.6, the code appears to get stuck whilst processing, and this happens until I stop the code.
When I run this using IDLE on my Mac, the code runs perfectly and the plot shows.
Seems to happen with plots lmplot and regplot, however boxplots etc do show as normal.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
df = pd.read_csv(csv.csv)
sns.regplot(x = 'independent', y = 'dependent', data = df)
The expected results should be a graph of the linear relationship between the two variables, however I am just getting a loading bar.
When I stop running the kernel, the graph exists as a scatterplot with no line of best fit. Of course this has the error in notebook as 'Keyboard Interrupted'.
Could this possibly be a bug? Thanks for your help.
Set ci parameter to none and it will solve your problem.
sns.regplot(x = 'independent', y = 'dependent', data = df, ci = None)

Plotly graph shows a blank space on GitHub

I am using Plotly to make graphs in my IPython notebook. I am able to view graphs on my IPython notebook when I upload them on GitHub they are displayed as blank spaces.
I read on the web that Plotly currently does not support iframes and hence the issue, but is there a workaround?
Here's the link to my GitHub Ipython notebook:
https://github.com/dhavalbhinde/bhinde_dhaval_spring2017/blob/master/Finals/Analysis%203.ipynb
Please, can someone advice how should I handle them?
I found a way to show Plotly plots on Github. They aren’t interactive anymore but it’s better than nothing.
First
import plotly.io as pio
pio.renderers
you can see the list of available renders.
*if you get an error on this step you can simply just install orca:
conda install -c plotly plotly-orca
and then there are 2 possible ways.
you can pass "svg" to .show() like this:
fig = px.scatter_3d(iris, x=transformed_iris['component1'], y=transformed_iris['component2'], z=transformed_iris['component3'],color='species')
fig.show(renderer="svg")
or you can set the pio.renderers.default to svg:
pio.renderers.default = "svg"
Import these and this and it will work :
from plotly.offline import plot, iplot, init_notebook_mode
import plotly.graph_objs as go
init_notebook_mode(connected=True)

Resources