python plot using pylab - python

I'm very new to python just started using it from a day or two..
I'm using Anaconda python notebook.
so I'm trying to plot, but in the output there is only grid and nothing no lines or anything,
my program is as follows
from __future__ import print_function
from decimal import *
import numpy as np
from sympy import *
import pylab
k = Symbol('k')
A = Symbol('A')
E = Symbol('E')
d = Symbol('d')
C = Symbol('C')
Y = Symbol('Y')
Y = []
for A in np.arange(-1.11, 1.11, 0.002):
s = sin(A)
c = cos(A)
C = (s/A) + c
Y.append(C)
pylab.plot(C, A)
grid()
xlabel('$x$')
ylabel('$y$')
title('graph')
The code doesn't show any errors, but will you please help me as to what am I doing wrong here ...

You are mixing different plotting functions from pylab, sympy and you are not giving an X axis:
import numpy as np
from matplotlib import pyplot
Y=[]
X = np.arange(-1.11, 1.11, 0.002)
for A in X:
s = np.sin(A)
c = np.cos(A)
C = (s/A)+c
Y.append(C)
line, = pyplot.plot(X,Y, "-b")
pyplot.grid(True)
pyplot.show()
Gives me:

What about showing the graph with
pylab.show()

If I do this, I have a figure with both grid and graph:
import pylab
pylab.plot([1, 3, 4], [1, 2, 3])
pylab.grid()
pylab.show()
But if I do this, I have first a figure with only the graph, and then with only the grid:
import pylab
pylab.plot([1, 3, 4], [1, 2, 3])
pylab.show() # here I get only the graph
pylab.grid()
pylab.show() # here I get only the grid
Note: calling grid(), title(), xlabel and ylabel as you do shall not work; each time it shall be prepended by pylab.. Is that really your code?

Related

Error bar in python:ErrorbarContainer object of 3 artists

I am trying to make an error plot but I get the error:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3])
y = np.array([17706973.57161736, 4605821.60887734, 2179197.59021156])
nor = np.array([1.21377113, 0.31571817, 0.14937884])
plt.errorbar(x, y, yerr = nor)
ErrorbarContainer object of 3 artists
and the plot does not contain error bars. Any idea?
What are you getting is not an error, it is the output of plt.errorbar. The reason you do not see the bars is because the scale of the error is way smaller than the scale of the data you are plotting. In fact, if you make the errors larger you will see them:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3])
y = np.array([17706973.57161736, 4605821.60887734, 2179197.59021156])
# Larger error.
nor = np.array([1.21377113 * 5000000, 0.31571817 * 5000000, 0.14937884 * 5000000])
plt.errorbar(x, y, yerr = nor)

Simple plotting of log function in python

I wrote a simple function to plot log in python:
import matplotlib.pyplot as plt
import numpy as np
x = list(range(1, 10000, 1))
y = [-np.log(p/10000) for p in x]
plt.scatter(x, y) # also tried with plt.plot(x, y)
plt.show()
I just want to see how the plot looks.
fn.py:5: RuntimeWarning: divide by zero encountered in log
y = [-np.log(p/10000) for p in x]
I get the above error and on top of that I get a blank plot with even the ranges wrong.
It is strange why there is divide by zero warning, when I am dividing by a number?
How can I correctly plot the function?
Although you have tagged python-3.x, it seems that you are using python-2.x where p/10000 will result in 0 for values of p < 10000 because the division operator / performs integer division in python-2.x. If that is the case, you can explicitly use 10000.0 instead of 10000 to avoid that and get a float division.
Using .0 is not needed in python 3+ because by default it performs float division. Hence, your code works fine in python 3.6.5 though
import matplotlib.pyplot as plt
import numpy as np
x = list(range(1, 10000, 1))
y = [-np.log(p/10000.0) for p in x]
plt.scatter(x, y)
plt.show()
On a different note: You can simply use NumPy's arange to generate x and avoid the list completely and use vectorized operation.
x = np.arange(1, 10000)
y = -np.log(x/10000.0)
Why import numpy and then avoid using it? You could have simply done:
from math import log
import matplotlib.pyplot as plt
x = xrange(1, 10000)
y = [-log(p / 10000.0) for p in x]
plt.scatter(x, y)
plt.show()
If you're going to bring numpy into the picture, think about doing things in a numpy-like fashion:
import matplotlib.pyplot as plt
import numpy as np
f = lambda p: -np.log(p / 10000.0)
x = np.arange(1, 10000)
plt.scatter(x, f(x))
plt.show()

Plotting random points with Python in Linux

I am a beginner at this, and I am needing to make a triangle and have it graphed on my VM in Linux. Using Python, the first step would be to generate just three random points for the triangle. How would be the best way to accomplish this? Any help, tips, or advice would be appreciated!
Using matplotlib as indicated in the tags:
import matplotlib.pyplot as plt
data = [[6, 2, 3], [1, 2, 3]]
plt.plot(data[0] + [data[0][0]], data[1] + [data[1][0]], marker='o', color='blue')
plt.show()
To generate random data: (look up the random module to choose the appropriate generator)
import random
data = [[random.randrange(10) for _ in range(3)], [random.randrange(10) for _ in range(3)]]
With pylab commands (Numpy and Matplotlib) you can do:
>>> a = rand(3, 2); a = vstack((a, a[0])); plot(a[:, 0], a[:, 1]); show()
You need something like python -i -c 'from pylab import *' to get the Numpy and Matplotlib functions in the namespace.

Using scipy.spatial.Delaunay in place of matplotlib.tri.Triangulation's built-in version

It appears as if matplotlib.tri.Triangulation uses a buggy and possibly incorrect implementation of Delaunay triangulation that is due to be replaced by qHull.
I'm trying to plot a trisurf using mpl_toolkits.mplot3d.plot_trisurf() and running into a bunch of exceptions that are unhelpful (IndexErrors and KeyErrors mostly, with no indication of what exactly went wrong).
Since scipy.spatial.Delaunay already uses qHull, I was wondering if there was a way to build a matplotlib.tri.Triangulation object for use with mpl_toolkits.mplot3d.plot_trisurf() using scipy's implementation of Delaunay triangulation.
I've tried passing the delaunay.points directly to matplotlib.tri.Triangulate via the triangles parameter, but this results in a ValueError: triangles min element is out of bounds.
http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.spatial.Delaunay.html
http://matplotlib.org/dev/api/tri_api.html
So you need to pass both the points and the triangles from qhull to the Triangulation constructor:
import numpy as np
import scipy.spatial
import matplotlib
import math
import matplotlib.tri as mtri
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# First create the x and y coordinates of the points.
n_angles = 20
n_radii = 10
min_radius = 0.15
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2*math.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += math.pi/n_angles
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
# Create the Delaunay tessalation using scipy.spatial
pts = np.vstack([x, y]).T
tess = scipy.spatial.Delaunay(pts)
# Create the matplotlib Triangulation object
x = tess.points[:, 0]
y = tess.points[:, 1]
tri = tess.vertices # or tess.simplices depending on scipy version
triang = mtri.Triangulation(x=pts[:, 0], y=pts[:, 1], triangles=tri)
# Plotting
z = x*x + y*y
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(triang, z)
plt.show()
output (with matplotlib current master):
#Marco was curious to know how to run this for a 2d array. I hope this would be useful. The list of vertices according to coordinates should be made an array and can be tessellated using mtri.Triangulation.
Sample code below:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
verts = np.array([[0.6,0.8],[0.2,0.9],[0.1,-0.5],[0.2,-2]])
triang = mtri.Triangulation(verts[:,0], verts[:,1])
plt.triplot(triang, marker="o")
plt.show()`enter code here`

How to make the histograms 'touch' in pylab?

So I made a program that does what I need, mainly plots histogram from my data, but I have a few issues with it:
Here's the program:
# -*- coding: cp1250 -*-
from __future__ import division
from numpy import *
from matplotlib import rc
from matplotlib.pyplot import *
import numpy as np
import matplotlib.pyplot as plt
data = loadtxt("mioni.txt", int)
nuz = len(data)
nsmp = 20
duz = int(nuz/nsmp)
L = []
for i1 in range(0,nsmp):
suma = 0
for i2 in range(0,duz):
suma += data[i1*duz+i2]
L.append(suma)
print L
plt.hist(L, 20, normed=1, facecolor='blue', alpha=0.75)
plt.xlabel('t(\mu s)')
plt.ylabel('Broj događaja')
plt.axis([0,10,0,300])
plt.grid(True)
plt.show()
EDIT: so I managed to deal with the ugly sums, but now my histograms don't work :(
Data is here: http://dropcanvas.com/kqjem
What's wrong? I get tons of errors and python crashes :\
The problem comes from having a discrete data set, it looks like you set the bins parameter to something that doesn't fit. Use the pylab.hist parameter histtype="stepfilled" to get them to touch without the lines. Here are a few examples:
import numpy as np
import pylab as plt
# Sample data
X1 = np.random.exponential(1.0,size=5000)
X2 = [int(z) for z in X1]
plt.subplot(221)
plt.hist(X1,bins=50)
plt.title('Continuous Data')
plt.subplot(222)
plt.hist(X2,bins=50)
plt.title('Discrete Data')
plt.subplot(223)
plt.hist(X2,histtype='stepfilled')
plt.title('Discrete Data Filled')
plt.show()
use numpy.histogram: http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
or matplotlib.pyplot.hist: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist
for example:
plt.hist(data, bins=20)

Categories