I'm having trouble plotting my results in Python, both in Ubuntu 14 and Windows 7 (both 64bit). As a simple comparison I did:
from tvb.simulator.lab import *
--> to import (among others) numpy as np and matplotlib.pyplot.
x = [1,2,3]
plot(x)
--> NameError: name 'plot' is not defined
When I looked up this error (plot is not defined) and followed these instructions, I get this result
matplotlib.lines.Line2D object at 0x7f8e31754dd0
without output...
Anyone who knows how I can fix this?
Assuming that your import (tvb.simulator.lab) does
import numpy as np
import matplotlib.pyplot
then you have to call plot like this:
matplotlib.pyplot.plot(x)
BUT, you could also reimport it in your script:
import matplotlib.pyplot as plt
and then use the alias plt (thats farely common):
plt.plot(x)
Related
I work with matplotlib. When I add the following lines, the figure is not displayed.
import matplotlib
matplotlib.use('Agg')
here is my code :
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plot
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plot.figure(figsize=(12,9))
def convert_sin_cos(x):
fft_axes = fig.add_subplot(331)
y = np.cos(x)
fft_axes.plot(x,y,'g*')
for i in range(3):
fft_axes = fig.add_subplot(332)
x=np.linspace(0,10,100)
fft_axes.plot(x,i*np.sin(x),'r+')
plot.pause(0.1)
convert_sin_cos(x)
Thanks
That's the idea!
When I run your code, the console says:
matplotlibAgg.py:15: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
How can it be useful? When you're running matplotlib code in a terminal with no windowing system, for example: a cluster (running the same code with different inputs, getting lot of results and without the need to move the data I can plot whatever I need).
I am trying to use the 3D scatter plot object in python. And I have successfully done this on my laptop. However, I can not copy and paste code onto my desktop. When I do this I get an error. I will attach my the section of my code below that is giving me trouble. I am using Anaconda to run my code. I will note that my laptop uses python 3.6 and my desktop uses 3.7, but I do not think that is causing it. The error I is get is as follows. "ValueError: Unknown projection '3d'"
import numpy as np
from scipy import optimize
import time
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import preprocessing
from sklearn.svm import SVR
import multiprocessing as mp
from obj_class import objective_class
import pdb
import scipy.integrate as integrate
def create3d():
grid_matrix = np.array([[1,1,1,1],[2,2,2,2],[3,3,3,3]])
fig = plt.figure()
ax = plt.axes(projection='3d')
p = ax.scatter3D(grid_matrix[:,0],grid_matrix[:,1] ,grid_matrix[:,2] , c=grid_matrix[:,3], cmap='viridis')
cb = fig.colorbar(p)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title(' Scatter Plot')
In order to use a 3d projection in matplotlib <= 3.1 you need to import axes3d, i.e.
from mpl_toolkits.mplot3d import Axes3D
From matplotlib >= 3.2, no extra import is necessary. So possibly you are running different matplotlib versions on both computers.
If you are running your code within an iPython kernel, Jupyter notebook for example,
then you only need to perform each import once and you will be able to run any code which relies on said import until the kernel is shutdown. However, in order to run the script in a self contained fashion you will need that import included in your script.
I'm really new to python, and I need to plot a data netcdf of sea surface temperature(sst),in python, but it keep giving erro.
I use the same code in another notebook, and it run perfect fine.
###SST CÓDIGO PLOT
import numpy as np
import matplotlib.pyplot as plt
from numpy import pi
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset
import pandas as pd
from scipy import stats
import seaborn as sns
import xarray as xr
import cartopy.crs as ccrs
import os
from netCDF4 import Dataset as netcdf_dataset
from cartopy import config
import statistics
import glob
import seaborn as sns
ds = xr.open_dataset('/home/mayna/Downloads/d86/20190327010000-OSISAF-L3C_GHRSST-SSTsubskin-GOES16-ssteqc_goes16_20190327_010000-v02.0-fv01.0.nc')
plt.figure(figsize=(8,4))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.add_feature(cartopy.feature.BORDERS, linestyle='-', linewidth=0.25)
ax.coastlines(linewidth=0.25)
ds['sea_surface_temperature'][0,:,:].plot.contourf(levels=20, ax=ax, transform=ccrs.PlateCarree(),cmap='coolwarm')
It say that erro is in the line "ax.add_feature(cartopy.feature.BORDERS, linestyle='-', linewidth=0.25)", that "NameError: name 'cartopy' is not defined".
What you think it is the problem?
P.S.: I know that I'm using a lot of lib that don't need
You seem to have never defined cartopy. Perhaps import cartopy at the top would solve your problem.
Name error in python means that the specific attribute/method is not imported in the program. In the code you are using cartopy.crs, cartopy.config and cartopy.features.Border, but only the first two are imported through your statements
import cartopy.crs as crash
and
from cartopy import config
So for features.Border, you either do
import cartopy
Or
from cartopy import features.Border #use just features.Border in that line if you are doing this.
For me, i installed cartopy package in jupyter but still it was showing error of cartopy not defined.(I was plotting the plots with cartopy.ccrs for stereographic plots)
solution: before importing and executing cartopy.ccrs just execute 'import cartopy' in the first line itself and then run the codes.It worked for me
Original question
I am new to Python and I am learning matplotlib. I am following the video tutorial recommended in the official User Manual of matplotlib: 'Plotting with matplotlib' by Mike Muller. The instructor does not show how he imports matplotlib but proceeds instantly with commands such as plot(x, linear, x, square), where x a sequence he has defined.
I tried to run
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
x = np.arange(100)
lines = plot(x, 'linear', 'g:+', x, 'square','r-o')
and got the error
NameError: name 'plot' is not defined
Updated question after solving the import issue
When I try to replicate the examples shown I get an error. Here is the code:
from matplotlib.pyplot import *
import numpy as np
import pandas as pd
x = np.arange(100)
lines = plot(x, 'linear', 'g:+', x, 'square','r-o')
ValueError: x and y must have same first dimension
Since I am simply repeating the commands shown in the tutorial I can not understand what I am doing wrong.
Your advice will be appreciated.
Short answer
You need to prefix all plotting calls with plt. like
lines = plt.plot(x, 'linear', 'g:+', x, 'square','r-o')
Longer answer
In Python functions that are not "builtin", i.e. always present, must be imported from modules.
In this case the line
from matplotlib import pyplot as plt
is the same as
import matplotlib.pyplot as plt
and means that you are importing the pyplot module of matplotlib into your namespace under the shorter name plt.
The pyplot module is where the plot(), scatter(), and other commands live.
If you don't want to write plt. before every plot call you could instead do
from matplotlib.pyplot import *
which will import all functions (symbols) into the global namespace, and you can now use your original line:
lines = plot(x, 'linear', 'g:+', x, 'square','r-o')
Edit: Problem with the plot() call
Your call to plot() is wrong, and the ValueError is telling you so.
You are trying to plot the string 'linear' (6 elements) against x which has 100 elements. Since they don't match, plot() tells you so.
My guess: linear and square should be expressions like
linear = x
square = x**2
In a python script, I just upgraded my matplotlib to 1.5.0 and am now getting this error:
from matplotlib import pyplot as plt
import matplotlib.ticker as tkr
from matplotlib import rcParams
from mpl_toolkits.basemap import Basemap, maskoceans
cs = m.contourf(x,y,mask_data,numpy.arange(min_range,max_range,step),cmap=PRGn_10.mpl_colormap)
NameError: global name 'PRGn_10' is not defined
How can I fix this?
It is not a matplotlib error. The error message says that the name PRGn_10 is not defined — because you never defined it. It is not present in any of your imports, and it is not a built-in, so Python cannot find it.
I am guessing you wanted to use the PRGn colormap. In order to do so, you need to import it, or the whole colormap module and reference it properly:
import matplotlib.cm as cm
cs = m.contourf(x,y,mask_data,numpy.arange(min_range,max_range,step),cmap=cm.PRGn)
or
from matplotlib.cm import PRGn
cs = m.contourf(x,y,mask_data,numpy.arange(min_range,max_range,step),cmap=PRGn)
Not sure what you meant by the .mpl_colormap bit, colormaps do not have such attribute.