ImportError: cannot import name '_path' - matplotlib

i must install matplotlib on a offline PC with python 3.5....to run some scripts. I copy the lib to the Right path on the offline PC....all other lib like reportlab are running. But if i trie to write something with matplotlib.pyplot as plt i got the Error Message "ImportError:cannot Import 'path'".
a the first step i
Import matplotlib
matplotlib.use('aggs')
Import matplotlib.pyplot as plt
the biggest Problem i cant download something on this offline pc.
So i am rly new to write some codes with python so pls dont jugde me guys =)
So the frist step was delet the old libs and use older versions of matplotlib
actuel i use 3.0.2.
i copy the Folders matplotlib, matplotlib-3.0.2.dist-info and matplotlib-3.0.2-py3.5-nspkg.pth
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(9.5, 6), dpi=450)
ax = fig.gca()
ax.set_xticks(np.arange(tick_scale_x))
ax.set_yticks(np.arange(tick_scale_y))
plt.title(dia_title, fontsize=20, color='black')
plt.xlabel(axis_label_x)
plt.ylabel(axis_label_y)

Related

Unable to generate plot using matplotlib

I am a beginner to Python and experimenting with a plot. the script runs fine but plot does not show up.
the matplotlib and numpy libraries are installed.
import numpy as np
f= h5py.File('3DIMG_05JUN2021_0000_L3B_HEM_DLY.h5','r')
#Studying the structure of the file by printing what HDF5 groups are present
for key in f.keys():
print(key) #Names of the groups in HDF5 file.
# will print the variables in the file
#Get the HDF5 group
ls=list(f.keys())
print("ls")
print(ls)
tsurf = f['HEM_DLY'][:]
print("tsurf")
print(tsurf)
tsurf1=np.squeeze(tsurf)
print(tsurf1.shape)
import matplotlib.pyplot as plt
im= plt.plot(tsurf1)
#plt.colorbar()
plt.imshow(im)```
Python version is 3 running on Ubuntu
Difficult to give you the exact answer without the dataset (please update the question with the dataset), but for sure, plt.plot does not return an object that can be plotted with plt.imshow
Try instead:
ax = plt.plot(tsurf1)
plt.show()
Probably the error was on the final plot.Try this:
import numpy as np
import matplotlib.pyplot as plt
f= h5py.File('/path','r')
ls=list(f.keys())
tsurf = f['your_key_str'][:]
tsurf1=np.squeeze(tsurf)
im= plt.plot(tsurf1)
plt.show(im) # <-- plt.show() NOT plt.imshow()

seaborn "kde jointplot" doesn't have color mapping in the latest version (0.11.0)

I was running seaborn ver. 0.10.1 on my jupyter notebook. This morning I upgraded to the latest version 0.11.0. Now, my kde jointplot doesn't give the color mapping that it used to. The code is the same. Only the versions are different.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib notebook
np.random.seed(1234)
v1 = pd.Series(np.random.normal(0,10,1000), name='v1')
v2 = pd.Series(np.random.normal(60,15,1000), name='v2')
v3 = pd.Series(2*v1 + v2, name='v3')
# set the seaborn style for all the following plots
sns.set_style('white')
sns.jointplot(v1, v3, kind='kde', space=0);
The function kdeplot (which is used internally by jointplot()to draw the bivariate density plot) has been extensively changed in v.0.11. See What's new and the documentation.
You now have to pass fill=True to get a filled KDE, and you need to specify thresh=0 if you want to fill the available space with color.
sns.jointplot(x=v1, y=v3, kind='kde', space=0, fill=True, thresh=0, cmap='Blues');

Getting an error : "OptionError: 'You can only set the value of existing options'" in python

I am getting an error:
"OptionError: 'You can only set the value of existing options'"
after using the below code, please can someone help?
### Data Analaysis
import numpy as np
import pandas as pd
### Data Visualization
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.graph_objs as go
import plotly.express as px
from plotly.subplots import make_subplots
from scipy.interpolate import make_interp_spline, BSpline
%matplotlib inline
import warnings
warnings.simplefilter(action='ignore', category=Warning)
pd.set_option('display.max_columns', None)
pd.options.plotting.backend = "plotly"
The option error "you can only set the value of existing options" are coming because of your last line of script
pd.options.plotting.backend = "plotly"
where you are trying to update your pandas backend plotting method.
Please update your pandas and plotly packages. Because it only works with pandas version>=0.25 and plotly version>=4.8.
So update both the packages, restart your kernel, if you are working on Jupyter notebook. For upgrading the packages
pip install -U pandas
pip install -U plotly

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 enable display of Matplotlib graphs with PyCharm?

When I run a program with PyCharm, it doesn't display graphs made with Matplotlib. E.g.:
import matplotlib.pyplot as plt
[...]
plt.imshow(montage(W / np.max(W)), cmap='coolwarm')
I tried calling
plt.interactive(False)
first, but it didn't make a difference.
Running the same program with ipython3, the graphs are displayed.
I set a default back-end for my system in matplotlibrc (TkAgg), and that did the trick.
The below code worked for me:
in pycharm-community-2018.2.2
import matplotlib.pyplot as plt
df.boxplot(column='ApplicantIncome')
plt.show()