How plot many points 3d in matplotlib - python

I am trying to plot 8000 points in three dimensions (x,y,z) of a terrain with matplotlib using the function contourf when I run the code I get the error
'OverflowError: In draw_path_collection: Exceeded cell block limit'
I tried to solve this with "mpl.rcParams['agg.path.chunksize'] = 20000"
but this did not resolve the issue. Here is my code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy.interpolate import griddata
import pandas as pd
import matplotlib as mpl
datos = pd.read_csv('zrh_terrain.txt', header =0)
dats=500
mpl.rcParams['agg.path.chunksize'] = 20000
X=datos.iloc[0:dats,0].values
Y=datos.iloc[0:dats,1].values
Z=datos.iloc[0:dats,2].values
dt_bar=np.linspace(Z.min(),Z.max(),10)
xi,yi= np.meshgrid(X,Y)
zi = griddata((X,Y),Z,(xi,yi),method='nearest')
plt.contourf(xi,yi,zi,extend='both',vmin=dt_bar[0],vmax=dt_bar[-1],
cmap=cm.terrain)

Related

Fourier series animation effect using by python ArtistAnimation

I'm studying about Fourier Series with python.
I drew it with cosine and sine function.
My code is like this.
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
x = Symbol('x')
fx=0
j=10
for i in range(1,j):
fx=fx+(2)/(np.pi*i)*(1-cos(i*np.pi))*(sin(i*x))
y_func=lambdify(x, fx, "numpy")
x_val=np.linspace(-np.pi,np.pi,315)
y_val=y_func(x_val)
plt.plot(x_val,y_val)
plt.show()
I could get the correct graph.
And I tried to make the graph into animaion effect like this gif file.
enter image description here
I wrote the code like below using by ArtistAnimation , but I couldn't get the animation.
How can i get the animation?
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
from matplotlib.animation import ArtistAnimation
x = Symbol('x')
fx=0
j=10
img=[]
fig, ax=plt.subplots(constrained_layout=True)
for i in range(1,j):
fx=fx+(2)/(np.pi*i)*(1-cos(i*np.pi))*(sin(i*x))
y_func=lambdify(x, fx, "numpy")
x_val=np.linspace(-np.pi,np.pi,315)
y_val=y_func(x_val)
fs=plt.plot(x_val,y_val)
img.append([fs])
anim=ArtistAnimation(fig,img,interval=5)
anim.save("Fourier_Series01.gif",fps=24)
I tried to make the code with ArtistAnimation
Thank you for your answer

How to make minimum point can see from above of surface plot?

I want to plot the surface graph and minimum point as follows:
I have tried to make python code:
import sympy
import numpy
from numpy import linalg
from numpy import linspace
from sympy import lambdify
import matplotlib.pyplot as plt
from matplotlib import cm
x1,x2=sympy.symbols('x1 x2')
f=x1**2-x1*x2-4*x1+x2**2-x2
lam_f = lambdify([x1,x2], f, modules=['numpy'])
x1value=linspace(-6,6,50)
x2value=linspace(-6,6,50)
x1value, x2value = numpy.meshgrid(x1value, x2value)
fvalue=lam_f(x1value,x2value)
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
surf = ax.plot_surface(x1value, x2value, fvalue, cmap=cm.jet,linewidth=0, antialiased=False,label="$f(x_1,x_2)$")
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
ax.set_zlabel('$f(x_1,x_2)$')
ax.scatter(3,2,-7,color="cyan",s=50,marker="s",zorder=2,linewidths=2)
plt.show()
The minimum point cannot see from above, but from below we can see the minimum point.
I want minimum point can see from above as the first picture. How to make it?

How to plot heat map with interpolation in python?

Code Output Image
Desired Image
[
My CSV data consists of X axis value, Y axis value and Hardness value and I wanted to plot smooth heat map rather than in boxes like.
DATA:
import cv2
from skimage.io import imread, imshow
from skimage.transform import resize
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
import os
from tqdm import tqdm
import pandas as pd
import seaborn as sns
from sklearn.neighbors import KernelDensity
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import style
from astropy.convolution import convolve, Gaussian2DKernel
from scipy.ndimage.filters import gaussian_filter
path = r"C:\Users\patels\Desktop\Ti/"
ids = os.listdir(path)
#print(ids)
for n, id_ in tqdm(enumerate(ids), total=len(ids)):
data = pd.read_excel(path+id_)
print(path+id_)
df1 = data[['HV 0.2', 'X pos. [mm]', 'Y pos. [mm]']]
heatmap1_data = pd.pivot_table(df1, values='HV 0.2', index=['Y pos. [mm]'], columns='X pos. [mm]')
plt.figure() #this creates a new figure on which your plot will appear
heatmap1 = sns.heatmap(heatmap1_data, cmap="viridis", vmin=300, vmax=400)
plt.title(ids[n]+'Ti Hardness Map')

How does `matplotlib` adjust plot to figure size?

How does matplotlib ensure that a dataset can be within plot with specified size.
How do i from a plot stored as numpy, How do i read the color of the pixels illustration a datapoint (0,4) - in the plot.
example:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from PIL import Image
import librosa
import librosa.display
from matplotlib import cm
fig = plt.figure(figsize=(12,4))
min = -1.828067
max = 22.70058
data = np.random.uniform(low=min, high=max, size=(474,40))
librosa.display.specshow(data.T,sr=16000,x_axis='frames',y_axis='mel',hop_length=160,cmap=cm.jet)
plt.show()
raw_input("sadas")
convert = plt.get_cmap(cm.jet)
numpy_output_static = convert(data.T)
plt.imshow(numpy_output_static, aspect = 'auto')
plt.show()
raw_input("asds")
First plot being :
Second plot being:
so the first has been resized to plot size 12,4 where the last basically plots the same data but just using the data shape as size... how do i change that?
Librosa just performs pcolormesh according to the GitHub source code
You need to define another figure with its own size for the second figure.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from PIL import Image
import librosa
import librosa.display
from matplotlib import cm
fig = plt.figure(figsize=(12,4))
min = -1.828067
max = 22.70058
data = np.random.uniform(low=min, high=max, size=(474,40))
librosa.display.specshow(data.T,sr=16000,x_axis='frames',y_axis='mel',hop_length=160,cmap=cm.jet)
plt.show()
raw_input("sadas")
convert = plt.get_cmap(cm.jet)
numpy_output_static = convert(data.T)
fig = plt.figure(figsize=(12,4))
plt.imshow(numpy_output_static, aspect = 'auto')
plt.show()
raw_input("asds")

Fir kernel distribution to my data

import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
import matplotlib as mpl
import seaborn as sns
from scipy.stats import gaussian_kde
from numpy import linspace,hstack
LINE_WIDTH = 3
filename=('')
data=[ map(float, line.split()) for line in open(filename,'r') if line.strip()]
dataM=np.array(data)
meandata=np.mean(dataM,axis=0)
SD = np.std(dataM,axis=0)
sns.set_palette("hls")
mpl.rc("figure", figsize=(8, 4))
xs = np.linspace(meandata[0]-(4 * SD[0]) ,meandata[0]+( 4 * SD[0]), dataM[:,0].size)
ys=dataM[:,0]
n,bins,patches=plt.hist(ys,15)
I get this plot.
and I want to get a kernel gaussian distribution plotted over my histogram but I am getting an error TypeError: 'module' object is not callable
When I am trying to do this
my_pdf = gaussian_kde(ys)
x = linspace(30,100,1000)
plt(x,my_pdf(x),'r') # distribution function
plt.hist(ys,normed=1,alpha=.3) # histogram
plt.show()
What am I doing wrong?
You can do this directly using seaborn. It would be something like this:
import pandas as pd
import seaborn as sns
import scipy.stats
import matplotlib.pyplot as plt
data = pd.read_csv('input.txt')
sns.distplot(data, kde=False, fit=scipy.stats.norm)
plt.show()
For a kde plot just do:
sns.distplot(data);

Categories

Resources