I am unable to import matplotlib.pyplot as plt in Rstudio.
I tried the solutions already available on SO.
Here are my attempts:
I installed reticulate package the devtools install way.
devtools::install_github(rstudio/reticulate)
library(reticulate)
repl_python()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10, 100)
plt.plot(x, x, label = "linear")
plt.legend()
plt.show()
I received the following error -
RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa ImportError: numpy.core.multiarray failed to import
I tried in RMarkdown as well.
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(reticulate)
use_condaenv(condaenv = "python36", conda = "auto", required = FALSE)
```
```{python}
repl_python()
import numpy as np
import matplotlib.pyplot as plt
n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)
plt.plot (X, Y+1, color='blue', alpha=1.00)
plt.plot (X, Y-1, color='blue', alpha=1.00)
plt.show()
```
Received the following error -
RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa
Traceback (most recent call last):
File "C:\Users\Vidhya\AppData\Local\Temp\Rtmp6vCzV6\chunk-code-13e83c491e61.txt", line 2, in <module>
import matplotlib.pyplot as plt
File "C:\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 29, in <module>
import matplotlib.colorbar
File "C:\Anaconda3\lib\site-packages\matplotlib\colorbar.py", line 32, in <module>
import matplotlib.artist as martist
File "C:\Anaconda3\lib\site-packages\matplotlib\artist.py", line 15, in <module>
from .transforms import (Bbox, IdentityTransform, TransformedBbox,
File "C:\Anaconda3\lib\site-packages\matplotlib\transforms.py", line 39, in <module>
from matplotlib._path import (affine_transform, count_bboxes_overlapping_bbox,
ImportError: numpy.core.multiarray failed to import
I had similar issues. I did following and it solved. Before that I would like to refer you in following threads from where I got the solution...
Qt platform plugin issue Rstudio
PyQt5 - Failed to load platform plugin "windows". Available platforms are: windows, minimal
Here is what you have to do [change the path according to your system]
In R:-
py_run_string("import os as os")
py_run_string("os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = 'C:/Dev/Anaconda/Library/plugins/platforms'")
np <- import("numpy", as = "np")
plt <- import("matplotlib.pyplot", as = "plt")
x <- np$linspace(0,10, 100)
plt$plot(x, x, label = "linear")
plt$legend()
plt$show()
In repl_python (embedded mode)
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10, 100)
plt.plot(x, x, label = "linear")
plt.legend()
plt.show()
Hope this helps... cheers
Related
I am trying to plot an image using SentinelHub-py. This is part of my the code:
from sentinelhub import SHConfig
config = SHConfig()
config.sh_client_id = "76186bb6-a02e-4457-9a9d-126e4fffaed4"
config.sh_client_secret = "aTlX[s:39vzA8p}HA{k*Zp!fJNF~(c7e.u7r21V!"
config.save()
%reload_ext autoreload
%autoreload 2
%matplotlib inline
#Import them
import os
import datetime
import numpy as np
import matplotlib.pyplot as plt
from sentinelhub import SHConfig
from sentinelhub import MimeType, CRS, BBox, SentinelHubRequest, SentinelHubDownloadClient, DataCollection, bbox_to_dimensions, DownloadRequest
from utils import plot_image
betsiboka_coords_wgs84 = [46.16, -16.15, 46.51, -15.58]
resolution = 60
betsiboka_bbox = BBox(bbox=betsiboka_coords_wgs84, crs=CRS.WGS84)
betsiboka_size = bbox_to_dimensions(betsiboka_bbox, resolution=resolution)
print(f'Image shape at {resolution} m resolution: {betsiboka_size} pixels')
"""
Utilities used by example notebooks
"""
import matplotlib.pyplot as plt
import numpy as np
def plot_image(image, factor=3.5/255, clip_range=(0,1)):
"""
Utility function for plotting RGB images.
"""
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(15, 15))
if clip_range is not None:
ax.imshow(np.clip(image * factor, *clip_range), **kwargs)
else:
ax.imshow(image * factor, **kwargs)
ax.set_xticks([])
ax.set_yticks([])
which give me the following error:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_6632/1226496077.py in <module>
9 from sentinelhub import MimeType, CRS, BBox, SentinelHubRequest, SentinelHubDownloadClient, DataCollection, bbox_to_dimensions, DownloadRequest
10
---> 11 from utils import plot_image
12
13 CLIENT_ID='76186bb6-a02e-4457-9a9d-126e4fffaed4'
ImportError: cannot import name 'plot_image' from 'utils' (c:\xxxxxxxxxxxx.py)
someone made a comment on this issue by saying:
"It seems that the utils package that you are calling is not the correct one. Try loading the utils.py from the examples folder, or that you can find [here][1] (i.e. copy the file to your working directory with your notebook)."
[1]: https://github.com/sentinel-hub/sentinelhub-py
I change my code to this:
"""
Utilities used by example notebooks
"""
import matplotlib.pyplot as plt
import numpy as np
def plot_image(image, factor=3.5/255, clip_range=(0,1)):
"""
Utility function for plotting RGB images.
"""
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(15, 15))
if clip_range is not None:
ax.imshow(np.clip(image * factor, *clip_range), **kwargs)
else:
ax.imshow(image * factor, **kwargs)
ax.set_xticks([])
ax.set_yticks([])
still didn't plot the image.
Please, any suggestions?
You have to navigate to your utils.py. In my computer is:
(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/utils).
Later, you have to copy and paste the next script from:
https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/utils.py
Finally, you will be able to type in your python script: "from utils import plot_image"
Best,
Jose
Trying to plot the graph using matplotlib which is been imported as plt but getting an error.
K-Mean Clustering
#importing libraries
import NumPy as np
import matplotlib as plt
import pandas as pd
#importing dataset with pandas
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3,4]].values
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
plt.plot(range(1, 11), wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()
Traceback (most recent call last):
File "<ipython-input-4-d9dfde180017>", line 8, in <module>
plt.plot(range(1, 11), wcss)
AttributeError: module 'matplotlib' has no attribute 'plot'
A 'has no attribute' error means the function or variable you're trying to access on an object doesn't exist. When you get this error from a library it means you did not read the library api documentations well enough.
matplotlib is the index of multiple apis, you may be looking for the pyplot api of matplotlib as this has a plot function.
See the documentation: https://matplotlib.org/api/pyplot_summary.html
See the index of matplotlib apis: https://matplotlib.org/api/index.html
Change
import matplotlib as plt
to
import matplotlib.pyplot as plt
The mpld3 (matplotlib on d3) example for LinkedBrush
http://mpld3.github.io/examples/linked_brush.html provides the following code example:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
import mpld3
from mpld3 import plugins, utils
data = load_iris()
X = data.data
y = data.target
# dither the data for clearer plotting
X += 0.1 * np.random.random(X.shape)
fig, ax = plt.subplots(4, 4, sharex="col", sharey="row", figsize=(8, 8))
fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95,
hspace=0.1, wspace=0.1)
for i in range(4):
for j in range(4):
points = ax[3 - i, j].scatter(X[:, j], X[:, i],
c=y, s=40, alpha=0.6)
# remove tick labels
for axi in ax.flat:
for axis in [axi.xaxis, axi.yaxis]:
axis.set_major_formatter(plt.NullFormatter())
# Here we connect the linked brush plugin
plugins.connect(fig, plugins.LinkedBrush(points))
mpld3.show()
While the public web page shows the matrix of linked outputs, when running it locally there is a json serialization error:
Traceback (most recent call last):
File "/git/scalatesting/src/main/python/mpld3_linkedbrush.py", line 34, in <module>
mpld3.show()
File "/usr/local/lib/python2.7/site-packages/mpld3/_display.py", line 358, in show
html = fig_to_html(fig, **kwargs)
File "/usr/local/lib/python2.7/site-packages/mpld3/_display.py", line 251, in fig_to_html
figure_json=json.dumps(figure_json, cls=NumpyEncoder),
File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 251, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/usr/local/lib/python2.7/site-packages/mpld3/_display.py", line 138, in default
return json.JSONEncoder.default(self, obj)
File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: array([ 1.]) is not JSON serializable
The local environment is
$pip show mpld3
Name: mpld3
Version: 0.3
Summary: D3 Viewer for Matplotlib
Home-page: http://mpld3.github.com
Author: Jake VanderPlas
Author-email: jakevdp#cs.washington.edu
License: BSD 3-clause
Location: /usr/local/lib/python2.7/site-packages
and
$python -V
Python 2.7.14
The mpld3 was installed today. Is there an mpld3 versioning issue? Any other suggestions?
Based on a comment from #snakecharmerb I forked from mpld3, entered the suggested fix, and pip installed from my new branch on github.
The fix is here: https://github.com/javadba/mpld3/tree/display_fix . It may be installed via:
python -m pip install --user "git+https://github.com/javadba/mpld3#display_fix"
It works well: the json serialization error is gone and the linkage among the 9 charts functions properly:
For me, the solution given here did not work.
I had a networkx graph to visualize:
import matplotlib.pyplot as plt
import numpy as np
import mpld3
import networkx as nx
G = nx.path_graph(4)
pos = nx.spring_layout(G)
fig, ax = plt.subplots(subplot_kw=dict(facecolor='#EEEEEE'))
scatter = nx.draw_networkx_nodes(G, pos, ax=ax)
nx.draw_networkx_edges(G, pos, ax=ax)
labels = G.nodes()
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)
mpld3.show()
Then it gave the "JSON not serializable" error. I found the above link, and tried the fix. The fix essentially says that if the object is of type numpy.ndarray, then change it to list.
But the object type of G.nodes is networkx.classes.reportviews.NodeView, not numpy.ndarray; thus it wasn't working.
So, I modified the file _display.py to add import networkx and added the following 2 lines in the default function in class NumpyEncoder to make it work:
elif isinstance(obj,networkx.classes.reportviews.NodeView):
return list(obj)
Now it works:
I really like the idea that cartopy can automatically plot in different map projections. However, I couldn't figure out how to do with the Iris cubes. As its a sister project, I expected that I might be able to. Is it possible to do something like this?
import iris as I
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
someCube = I.load('someCube.pp')
ax = plt.axes(projection=ccrs.Robinson())
I.plot.contourf(someCube, transform=ccrs.Robinson())
plt.show()
thanks
I took your pseudo code and made it runnable with Iris' sample data:
import iris
import iris.plot as iplt
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
fname = iris.sample_data_path('air_temp.pp')
air_temp = iris.load_cube(fname)
ax = plt.axes(projection=ccrs.Robinson())
iplt.contourf(air_temp, transform=ccrs.Robinson(central_longitude=180))
ax.coastlines()
plt.show()
If you run this code, you will get an exception along the lines of:
Traceback (most recent call last):
File "using_custom_projections.py", line 11, in <module>
iris.plot.contourf(air_temp, transform=ccrs.Robinson())
File "lib/iris/plot.py", line 452, in contourf
result = _draw_2d_from_points('contourf', None, cube, *args, **kwargs)
File "lib/iris/plot.py", line 263, in _draw_2d_from_points
result = _map_common(draw_method_name, arg_func, iris.coords.POINT_MODE, cube, data, *args, **kwargs)
File "lib/iris/plot.py", line 406, in _map_common
assert 'transform' not in kwargs, 'Transform keyword is not allowed.'
AssertionError: Transform keyword is not allowed.
Which is trying to tell you that you do not need to tell it which "transform" (or coordinate system) the cube is in. The reason for that is that an Iris cube should contain full metadata about the underlying data: the coordinate systems is part of that metadata.
So, to get the example to work, you can simply remove the transform keyword argument in your contourf call:
import iris
import iris.plot as iplt
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
fname = iris.sample_data_path('air_temp.pp')
air_temp = iris.load_cube(fname)
ax = plt.axes(projection=ccrs.Robinson(central_longitude=180))
iplt.contourf(air_temp)
ax.coastlines()
plt.show()
There is a similar example in the iris gallery, specifically http://scitools.org.uk/iris/docs/latest/examples/graphics/rotated_pole_mapping.html#rotated-pole-mapping-03 (the very last plot in the example).
HTH,
So I'd like to plot simple gamma function, but I have some problems. My code is:
#!/usr/bin/env python
# -*- coding: cp1250 -*-
#import math
from scipy.special import *
#from scitools.std import *
from pylab import *
def f1(x):
return gamma(x)
x = linspace(-6, 6, 512)
y1 = f1(x)
# Matlab-style syntax:
plot(x, y1)
xlabel('x')
ylabel('y')
legend(r'$\Gamma(x)$')
grid(True)
show()
I tried importing the gamma function from math, and from scipy.special but I get the following error:
Traceback (most recent call last): File "D:/faxstuff/3.godina/kvantna/plotgamma.py", line 13, in y1 = f1(x) File "D:/faxstuff/3.godina/kvantna/plotgamma.py", line 9, in f1 return gamma(x) File "mtrand.pyx", line 1599, in mtrand.RandomState.gamma (numpy\random\mtrand\mtrand.c:8389) ValueError: shape <= 0
How to do it? This should be easy, but I seem to fail :(
One of the modules (pylab, I think) is shadowing the gamma function by the gamma random variable function. This works, but I had to turn off the call to legend (I'm not sure why, yet).
from scipy.special import gamma as Gamma
#from scitools.std import *
from pylab import *
def f1(x):
return Gamma(x)
x = linspace(-6, 6, 512)
y1 = f1(x)
gca().set_autoscale_on(False)
# Matlab-style syntax:
plot(x, y1)
xlabel('x')
ylabel('y')
# legend(r'$\Gamma(x)$')
axis([-6, 6, -100, 100])
grid(True)
show()
Try this in a Sage notebook:
# Simple example demonstrating how to interact with matplotlib directly.
# Comment plt.clf() to get the plots overlay in each update.
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
#interact
def plot_gamma(a=(1,(1,10)), loc=(0,(0,10)), scale=(1,(1,10))):
rv = stats.gamma(a, loc, scale)
x = np.linspace(-1,20,1000)
plt.plot(x,rv.pdf(x))
plt.grid(True)
plt.savefig('plt.png')
plt.clf()