Python version of h=area() in Matlab - python

I asked a related question yesterday and fortunately got my answer from jlarsch quickly. But now I am stuck with the next part, which starts with the h=area() line. I'd like to know the python version of the area() function, via which I will be able to set the colors. Could someone shed me some light again? Thanks much in advance.
...
Subplot (2,1,1);
H = plot (rand(100,5));
C = get (H, 'Color')
H = area (myX, myY);
H(1).FaceColor = C(1);
H(2).FaceColor = C(2);
Grid on;
...

The pretty much exact equivalent of MATLAB's Area plot is matplotlib's stackplot. Here is the first MATLAB example from the above link reproduced using matplotlib:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(4)
y = [[1, 3, 1, 2],
[5, 2, 5, 6],
[3, 7, 3, 1]]
plt.stackplot(x, y)
plt.show()
And here is the result:

You might be looking for pygame.draw.polygon(), which can fill a polygon defined by an arbitrary array of points.

You probably want plt.fill().
A huge amount of graph types at Matplotlib Gallery

Related

Find intersection point between two curves [duplicate]

This question already has an answer here:
How to find the exact intersection of a curve (as np.array) with y==0?
(1 answer)
Closed last year.
I have two curves (supply and demand) and I want to find their intersection point (both, x and y). I was not able to find a simple solution for the mentioned problem. I want my code in the end to print what is the value of X and what is the value of Y.
supply = final['0_y']
demand = final['0_x']
price = final[6]
plt.plot(supply, price)
plt.plot(demand, price)
The main problem and challenge (something wrong) are that I have tried every other method, and every single time I get an empty set/list. Even when I try to visualize the intersection, I also get empty visual.
GRAPH:
As the implementation of the duplicate is not straightforward, I will show you how you can adapt it to your case. First, you use pandas series instead of numpy arrays, so we have to convert them. Then, your x- and y-axes are switched, so we have to change their order for the function call:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
final = pd.DataFrame({'0_y': [0, 0, 0, 10, 10, 30],
'0_x': [20, 11, 10, 4, 1, 0,],
"6": [-200, 50, 100, 200, 600, 1000]})
supply = final['0_y'].to_numpy()
demand = final['0_x'].to_numpy()
price = final["6"].to_numpy()
plt.plot(supply, price)
plt.plot(demand, price)
def find_roots(x,y):
s = np.abs(np.diff(np.sign(y))).astype(bool)
return x[:-1][s] + np.diff(x)[s]/(np.abs(y[1:][s]/y[:-1][s])+1)
z = find_roots(price, supply-demand)
x4z = np.interp(z, price, supply)
plt.scatter(x4z, z, color="red", zorder=3)
plt.title(f"Price is {z[0]} at supply/demand of {x4z[0]}")
plt.show()
Sample output:

How to create a histogram in Python one data point at a time?

I need to create a histogram of a very large data set in python 3. However, I cannot use a list to create a histogram because the list would be too large given my data. I need a way to update a histogram as each data point is created. That way my computer is only ever dealing with a single point and updating the plot.
I've been using matplotlib. Tried plt.draw() but couldn't get it to work. (See code below)
#Proof of concept code
l = [1, 2, 3, 2, 3, 2]
n = 0
p = False
for x in range(0,6):
n = l[x]
if p == False:
fig = plt.hist(n)
p = True
else:
plt.draw()
I need a plot that looks like plt.hist(l). But have only been getting the first point plotted.
Are you familiar with Numpy? Numpy handles large arrays pretty well.
Here's an example using a random integer set from 1 to 3 (inclusive).
import matplotlib.pyplot as plt
import numpy as np
arr_random = np.random.randint(1,4,10000)
plt.hist(arr_random)
plt.show()
It's very efficient to compute plt.hist() with Numpy arrays.

How to generate image by using python and given data?

I have one data file which is like this:
1, 23%
2, 33%
3, 12%
I want to use python to generate one histogram to represent the percentage. I followed these command:
from PIL import Image
img = Image.new('RGB', (width, height))
img.putdata(my_data)
img.show()
However I got the error when I put the data: SystemError: new style getargs format but argument is not a tuple. Do I have to change my data file? and How?
A histogram is usually made in matplotlib by having a set of data points and then assigning them into bins. An example would be this:
import matplotlib.pyplot as plt
data = [1, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7]
plt.hist(data, 7)
plt.show()
You already know what percentage of your data fits into each category (although, I might point out your percentages don't add to 100...). A way to represent this is to to make a list where each data value is represented a number of times equal to its percentage like below.
data = [1]*23 + [2]*33 + [3]*12
plt.hist(data, 3)
plt.show()
The second argument to hist() is the number of bins displayed, so this is likely the number you want to make it look pretty.
Documentation for hist() is found here:
http://matplotlib.org/api/pyplot_api.html
Are you graphing only? PIL is an image processing module - if you want histograms and other graphs you should consider matplotlib.
I found an example of a histogram here.

Is there a solid method for wavelet analysis in Python?

all. So, I have some time series data that I'd like to process with a wavelet transform to represent thusly. I am relatively new to the concept of wavelets. I noticed scipy.signal has a few objects, but it seems thin. Is there a library or something out there that will aid in this? Any documentation or tutorials you know of will be greatly appreciated.
Have you tried PyWavelets?
import pywt
x = [3, 7, 1, 1, -2, 5, 4, 6]
# Discrete Wavelet Transform
cA, cD = pywt.dwt(x, 'db2')
x2 = pywt.idwt(cA, cD, 'db2')
There are a few examples in their documentation.
The GitHub repository has more updated information to check out as well.

annotating many points with text in mayavi using mlab

I'm trying to annotate points plotted with the points3d() function using mayavi.mlab.
Each point is associated with a label which I would like to plot next to the points using the text3d() function. Plotting the points is fast, however the mlab.text3d() function does not seem to accept arrays of coordinates, so I have to loop over the points and plot the text individually, which is very slow:
for i in xrange(0, self.n_labels):
self.mlab_data.append(
mlab.points3d( pX[self.labels == self.u_labels[i], 0],
pX[self.labels == self.u_labels[i], 1],
pX[self.labels == self.u_labels[i], 2],
color=self.colours[i],
opacity=1,
scale_mode="none",
scale_factor=sf ) )
idcs, = np.where(self.labels == self.u_labels[i])
for n in idcs.flatten():
mlab.text3d( pX[n, 0],
pX[n, 1],
pX[n, 2],
"%d" % self.u_labels[i],
color=self.colours[i],
opacity=1,
scale=sf )
Any ideas how I could speed this up? Also, is it possible to add a legend (as for instance in matplotlib), I couldn't find anything in the docs.
Thanks,
Patrick
The way you are doing it above will render the scene every time you plot a point or text. This is slow. You can disable the scene rendering, do the plotting and then render the scene by figure.scene.disable_render = True/False:
import scipy
from mayavi import mlab
X = 100 * scipy.rand(100, 3)
figure = mlab.figure('myfig')
figure.scene.disable_render = True # Super duper trick
mlab.points3d(X[:,0], X[:,1], X[:,2], scale_factor=0.4)
for i, x in enumerate(X):
mlab.text3d(x[0], x[1], x[2], str(i), scale=(2, 2, 2))
figure.scene.disable_render = False # Super duper trick
I use this trick and others in Figure class in morphic Viewer https://github.com/duanemalcolm/morphic/blob/master/morphic/viewer.py
Another good trick in the code is to reuse existing objects, i.e., if you've plotted the text already, don't replot them, just update their position and text attributes. This means saving the mlab object. You can see how I do this in morphic.Viewer.

Categories

Resources