TclError when creating plots using mpld3 in pythonanywhere - matplotlib

I am creating plots using matplotlib and mpld3 (both successfully installed) but when plotting I got this error message:
...File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1767, in init#012 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)#012TclError: no display name and no $DISPLAY environment variable.
Any idea how to solve that?
thanks for your help

Try this
import matplotlib
matplotlib.use('Agg')
Check this page for more informations

Related

JupyterLab fig does not show. It shows blank result (but works fine on jupyternotebook)

I am new to JupyterLab trying to learn.
When I try to plot a graph, it works fine on jupyter notebook, but does not show the result on jupyterlab. Can anyone help me with this?
Here are the codes below:
import pandas as pd
import pandas_datareader.data as web
import time
# import matplotlib.pyplot as plt
import datetime as dt
import plotly.graph_objects as go
import numpy as np
from matplotlib import style
# from matplotlib.widgets import EllipseSelector
from alpha_vantage.timeseries import TimeSeries
Here is the code for plotting below:
def candlestick(df):
fig = go.Figure(data = [go.Candlestick(x = df["Date"], open = df["Open"], high = df["High"], low = df["Low"], close = df["Close"])])
fig.show()
JupyterLab Result:
Link to the image (JupyterLab)
JupyterNotebook Result:
Link to the image (Jupyter Notebook)
I have updated both JupyterLab and Notebook to the latest version. I do not know what is causing JupyterLab to stop showing the figure.
Thank you for reading my post. Help would be greatly appreciated.
Note*
I did not include the parts for data reading (Stock OHLC values). It contains the API keys. I am sorry for inconvenience.
Also, this is my second post on stack overflow. If this is not a well-written post, I am sorry. I will try to put more effort if it is possible. Thank you again for help.
TL;DR:
run the following and then restart your jupyter lab
jupyter labextension install #jupyterlab/plotly-extension
Start the lab with:
jupyter lab
Test with the following code:
import plotly.graph_objects as go
from alpha_vantage.timeseries import TimeSeries
def candlestick(df):
fig = go.Figure(data = [go.Candlestick(x = df.index, open = df["1. open"], high = df["2. high"], low = df["3. low"], close = df["4. close"])])
fig.show()
# preferable to save your key as an environment variable....
key = # key here
ts = TimeSeries(key = key, output_format = "pandas")
data_av_hist, meta_data_av_hist = ts.get_daily('AAPL')
candlestick(data_av_hist)
Note: Depending on system and installation of JupyterLab versus bare Jupyter, jlab may work instead of jupyter
Longer explanation:
Since this issue is with plotly and not matplotlib, you do NOT have to use the "inline magic" of:
%matplotlib inline
Each extension has to be installed to the jupyter lab, you can see the list with:
jupyter labextension list
For a more verbose explanation on another extension, please see related issue:
jupyterlab interactive plot
Patrick Collins already gave the correct answer.
However, the current JupyterLab might not be supported by the extension, and for various reasons one might not be able to update the JupyterLab:
ValueError: The extension "#jupyterlab/plotly-extension" does not yet support the current version of JupyterLab.
In this condition a quick workaround would be to save the image and show it again:
from IPython.display import Image
fig.write_image("image.png")
Image(filename='image.png')
To get the write_image() method of Plotly to work, kaleido must be installed:
pip install -U kaleido
This is a full example (originally from Plotly) to test this workaround:
import os
import pandas as pd
import plotly.express as px
from IPython.display import Image
df = pd.DataFrame([
dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"),
dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Resource="Alex"),
dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Resource="Max")
])
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Resource")
if not os.path.exists("images"):
os.mkdir("images")
fig.write_image("images/fig1.png")
Image(filename='images/fig1.png')

How to show graph in Atom using PyPlot

I am using Julia in Atom on a MacBook Pro and I do not succeed in getting a plot Window within or outside Atom when I use PyPlot.
Here is the package status :
....
(v1.1) pkg> status
Status `~/.julia/environments/v1.1/Project.toml`
[c52e3926] Atom v0.8.2
[7073ff75] IJulia v1.18.0
[e5e0dc1b] Juno v0.7.0
[d330b81b] PyPlot v2.8.0
[ade2ca70] Dates
...
I try the following code :
...
using PyPlot
plot(rand(10))
...
And I get :
...
1-element Array{PyCall.PyObject,1}:
PyObject <matplotlib.lines.Line2D object at 0x12963c9e8>
....
If I try :
...
plt.show()
...
I get :
...
/Users/Didier/.julia/conda/3/lib/python3.7/sitepackages/matplotlib/figure.py:445: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
% get_backend())
...
There are plenty discussions about Backends with PyPlot (i.e. Matplotlib inside Julia) but nowhere I found a rationale to modify the backend used by Matplotlib within Atom.
Does somebody have a clear idea about this?
Thanks in advance.
Use PyPlot.display_figs() as in this example:
using PyPlot
plot(1:5,(1:5).^2)
PyPlot.display_figs()
When working in the console PyPlot.show() could be a good idea.
Finally, you can always just save your picture to a file with the savefig command e.g. savefig(raw"c:\temp\aa.png")

Julia: How to save a figure without plotting/displaying it in PyPlot?

I am using the PyPlot package in Julia to generate and save several figures. My current approach is to display the figure and then save it using savefig.
using PyPlot
a = rand(50,40)
imshow(a)
savefig("a.png")
Is there a way to save the figure without having to first display it?
Are you using the REPL or IJulia?
If you close the figure then it won't show you the plot. Is that what you want?
a = rand(50,40)
ioff() #turns off interactive plotting
fig = figure()
imshow(a)
close(fig)
If that doesn't work you might need to turn off interactive plotting using ioff() or change the matplotlib backend (pygui(:Agg)) (see here: Calling pylab.savefig without display in ipython)
Remember that most questions about plotting using PyPlot can be worked out by reading answers from the python community. And also using the docs at https://github.com/JuliaPy/PyPlot.jl to translate between the two :)
close() doesn't require any arguments so you can just call close() after saving the figure and create a new figure
using PyPlot
a = rand(50,40)
imshow(a)
savefig("a.png")
# call close
close()

Matplotlib : Set default value for plt.axis to "equal"

I have many plots to draw and I wish to see all of them with the option plt.axis("equal").
Is there a way to fix Matplotlib default settings to plt.axis("equal") (as what is proposed by matplotlib.rcParams for most of the Matplolib paramaters) ?
Thanks,
Patrick
I have created an issue / feature request (8088) for this.
As it was pointed out there this rcParams doesn't work for pyplot.plot() yet. Hopefully it will be implemented soon.
However, the following works already and is the solution in case of images:
import matplotlib.pyplot as plt
plt.rcParams['image.aspect'] = 'equal'
a=[[1],[2]]
plt.imshow(a)

matplotlib get rid of max_open_warning output

I wrote a script that calls functions from QIIME to build a bunch of plots among other things. Everything runs fine to completion, but matplotlib always throws the following feedback for every plot it creates (super annoying):
/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py:412: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam figure.max_num_figures).
max_open_warning, RuntimeWarning)
I found this page which seems to explain how to fix this problem , but after I follow directions, nothing changes:
import matplotlib as mpl
mpl.rcParams[figure.max_open_warning'] = 0
I went into the file after calling matplotlib directly from python to see which rcparams file I should be investigating and manually changed the 20 to 0. Still no change. In case the documentation was incorrect, I also changed it to 1000, and still am getting the same warning messages.
I understand that this could be a problem for people running on computers with limited power, but that isn't a problem in my case. How can I make this feedback go away permanently?
Try setting it this way:
import matplotlib as plt
plt.rcParams.update({'figure.max_open_warning': 0})
Not sure exactly why this works, but it mirrors the way I have changed the font size in the past and seems to fix the warnings for me.
Another way I just tried and it worked:
import matplotlib as mpl
mpl.rc('figure', max_open_warning = 0)
When using Seaborn you can do it like this
import seaborn as sns
sns.set_theme(rc={'figure.max_open_warning': 0})
Check out this article which basically says to plt.close(fig1) after you're done with fig1. This way you don't have too many figs floating around in memory.
In Matplotlib, figure.max_open_warning is a configuration parameter that determines the maximum number of figures that can be opened before a warning is issued. By default, the value of this parameter is 20. This means that if you open more than 20 figures in a single Matplotlib session, you will see a warning message. You can change the value of this parameter by using the matplotlib.rcParams function. For example:
import matplotlib.pyplot as plt
plt.rcParams['figure.max_open_warning'] = 50
This will set the value of figure.max_open_warning to 50, so that you will see a warning message if you open more than 50 figures in a single Matplotlib session.