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
Related
I just downloaded the ProPlot package and am wondering how I can make a scatter plot. I looked into this example, but as I tried
import proplot as plt
plt.figure(...)
plt.scatter(...)
it returns me AttributeError: module 'proplot' has no attribute 'scatter' . My plot worked when I did
import proplot as plt
import matplotlib.pyplot as plt
plt.figure(...)
plt.scatter(...)
And I did see the effect of proplot in this way. However, I don't think it's right to import two packages with the same notation plt. Is there a better way I can generate the scatter plot using proplot? Thanks!
Proplot does not offer a direct replacement for the scatter plot at the top level of the proplot module. The only way to construct it is to call the method of an axis object:
import proplot as pplt
fig, ax = pplt.subplots()
ax.scatter()
Or alternatively:
fig = pplt.figure()
ax = fig.subplot()
ax.scatter(...)
Note that if you import matplotlib after proplot under the same name plt alias, you won't be able to use the proplot interface under plt since it'll be replaced by matplotlib. It is not "wrong" to do so, since it is legal python, but surely not what you intended to accomplish.
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 want to plot but I face some errors
import numpy as np
import matplotlib as plt
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()
what is its problem?
cannot find reference 'arange' in __ init__.py
I'm using pycharm on windows 10
is there any difference between matplotlib.py and matplotlib.pyplot?
I can not find the second one
solved: use version 2.1.2
Your import of matplotlib is not correct.
Use import matplotlib.pyplot as plt (notice the extra .pyplot in there)
It'll should run properly.
the problem was with my version of matplotlib
I've installed v.2.2.0. uninstalled it and installed v.2.1.2 then this code start working.
Well first check the versions of your numpy and matplotlib libraries and your code:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()
works fine..
It gives me output like this:
So, maybe the problem is with your versions, Moreover, It seems that your numpy package is not installed correctly according to your error. install numpy package and then again run your code.
also add matplotlib.pyplot instead or only matplotlib
Also check this: Matplotlib, Pylab, Pyplot, etc: What's the difference between these and when to use each?
Hope this will help you! :)
I have written a relatively simple function in python that can be used to plot the time domain history of a data set as well as the frequency domain response of a data set after a fast fourier transform. In this function I use the command from pylab import * to bring in all the necessary functionality. However, despite successfully creating the plot, I get a warning stating
import * only allowed at the module level.
So if using the command from pylab import * is not the preferred methodology, how do I properly load all the necessary functionality from pylab. The code is attached below. Also, is there a way to close the figure after the function is exited, I have tried plt.close() which is not recognized for subplots?
def Time_Domain_Plot(Directory,Title,X_Label,Y_Label,X_Data,Y_Data):
# Directory: The path length to the directory where the output file is
# to be stored
# Title: The name of the output plot, which should end with .eps or .png
# X_Label: The X axis label
# Y_Label: The Y axis label
# X_Data: X axis data points (usually time at which Yaxis data was acquired
# Y_Data: Y axis data points, usually amplitude
from pylab import *
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
Output_Location = Directory.rstrip() + Title.rstrip()
fig,plt = plt.subplots()
matplotlib.rc('xtick',labelsize=18)
matplotlib.rc('ytick',labelsize=18)
plt.set_xlabel(X_Label,fontsize=18)
plt.set_ylabel(Y_Label,fontsize=18)
plt.plot(X_Data,Y_Data,color='red')
fig.savefig(Output_Location)
plt.clear()
From the matplotlib documentation:
pylab is a convenience module that bulk imports matplotlib.pyplot (for plotting) and numpy (for mathematics and working with arrays) in a single name space. Although many examples use pylab, it is no longer recommended.
I would recommend not importing pylab at all, and instead try using
import matplotlib
import matplotlib.pyplot as plt
And then prefixing all of your pyplot functions with plt.
I also noticed that you assign the second return value from plt.subplots() to plt. You should rename that variable to something like fft_plot (for fast fourier transform) to avoid naming conflicts with pyplot.
With regards to your other question (about fig, save fig()) you're going to need to drop that first fig because it's not necessary, and you'll call savefig() with plt.savefig() because it is a function in the pyplot module. So that line will look like
plt.savefig(Output_Location)
Try something like this:
def Time_Domain_Plot(Directory,Title,X_Label,Y_Label,X_Data,Y_Data):
# Directory: The path length to the directory where the output file is
# to be stored
# Title: The name of the output plot, which should end with .eps or .png
# X_Label: The X axis label
# Y_Label: The Y axis label
# X_Data: X axis data points (usually time at which Yaxis data was acquired
# Y_Data: Y axis data points, usually amplitude
import matplotlib
from matplotlib import rcParams, pyplot as plt
rcParams.update({'figure.autolayout': True})
Output_Location = Directory.rstrip() + Title.rstrip()
fig,fft_plot = plt.subplots()
matplotlib.rc('xtick',labelsize=18)
matplotlib.rc('ytick',labelsize=18)
fft_plot.set_xlabel(X_Label,fontsize=18)
fft_plot.set_ylabel(Y_Label,fontsize=18)
plt.plot(X_Data,Y_Data,color='red')
plt.savefig(Output_Location)
plt.close()
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)