Related
this python program is meant to picture a graph with vectors but python returns this: "TypeError: 'int' object is not subscriptable" for last plt.arrow(). I don't know if anyone can help me but I would be glad if someone could resolve this problem. Thanks in advance for your help !
# cellule 1: importation des différentes bibliothèques
from lycee import *
import matplotlib.pyplot as plt
import numpy as np
# cellule 2: coordonnées de la position du satellite
R = 42164000 # rayon en mètre
T = 84164 # période de révolution
t = np.arange(0, 84164, 500) # dates en secondes
a = 2*np.pi/T*t # α=2π/T*t
x = R*np.cos(a) # x=Rcosα
y = R*np.sin(a) # y=Rsinα
# cellule 3: coordonnées du vecteur vitesse (vx,vy)
def coordvit(t, u):
vu = []
for i in range(len(u)-1):
vui = (u[i+1]-u[i]/(t[i+1]-t[i]))
vu.append(vui)
return vu
vx = coordvit(x, t)
vy = coordvit(y, t)
# cellule 4: coordonnées du vecteur accélération
def coordaccelerer(vu, t):
au = []
for j in range(len(vu)-1):
auj = (vu[j+1]-vu[j]/(t[j+1]-t[j]))
au.append(auj)
return au
ax = coordaccelerer(vx, t)
ay = coordaccelerer(vy, t)
# cellule 5: coordonnées du vecteur force gravitationnelle
MT = 5.972*10**24 # masse de la Terre en kg
m = 4192 # masse du satellite après avoir consommé 1000kg de carburant, en kg
G = 6.67408*10**(-11) # consante de gravitation universelle en m^3.kg^-1.s^-2
Fx = (G*MT*m/(R**2))*(-x/R)
Fy = 0
# cellule 6: tracé du graphique (trajectoire du satellite, vecteurs accélération et force gravitationnelle)
plt.figure("acceleration et fg d'un satellite", figsize=(10, 10))
plt.plot(x, y, "r+-")
plt.xlabel("x en m")
plt.ylabel("y en m")
plt.xlim(-50000000, 50000000)
plt.ylim(-50000000, 50000000)
plt.title("Mouvement d'un satellite géostationnaire autour de la Terre \nComparaison des vecteurs accélération et ""force gravitationnelle")
for k in range(len(ax)):
plt.arrow(x[k], y[k], 50*ax[k], 500*ay[k], facecolor="b", edgecolor="b", width=20000, head_width=1000000, length_includes_head=True) # tracé vecteur accélération
plt.arrow(x[k], y[k+1], 50*Fx[k], 500*Fy[k], facecolor="r", edgecolor="r", width=20000, head_width=1000000, length_includes_head=True) # tracé vecteur fg
plt.show()
The last plt.arrow is where it doesn't work !
Response to an answer to my initial question by Green Cloak Guy:
I'm pretty sure it's the same. Here is my friend's code which runs perfectly:
# importation des différentes bibliothèques
from lycee import *
import matplotlib.pyplot as plt
import numpy as np
# cellule 2 : coordonnées de la position du satellite
R = 42164000 # rayon en mètre
T = 84164 # période de révolution en seconde
t = np.arange(0, 84164, 500)
alpha = 2 * np.pi / T * t # α=2π/T*t
x = R * np.cos(alpha) # x=Rcosα
y = R * np.sin(alpha) # y=Rsinα
# cellule 3 : coordonnées du vecteur vitesse (vx,vy) à l'aide de la création d'une fonction
def coordvit(t, u):
vu = []
for i in range(len(u) - 1):
vui = (u[i + 1] - u[i]) / (t[i + 1] - t[i])
vu.append(vui)
return vu
vx = coordvit(t, x)
vy = coordvit(t, y)
# cellule 4 : Coordonnées du vecteur accélération
def coordaccelerer(vu, t):
au = []
for j in range(len(vu) - 1):
auj = (vu[j + 1] - vu[j]) / (t[j + 1] - t[j])
au.append(auj)
return au
ax = coordaccelerer(vx, t)
ay = coordaccelerer(vy, t)
# cellule 5 : Coordonnées du vecteur force gravitationnelle
MT = 5.972 * 10 ** 24 # masse de la Terre en kg
m = 4192 # masse du satellite après avoir consommé 1000 kg de carburant
G = 6.67408 * 10 ** (-11) # constante de gravitation universelle en m^3.kg^-1.s^-2
Fx = (G * MT * m / (R ** 2)) * (-x / R)
Fy = (G * MT * m / (R ** 2)) * (-y / R)
# cellule 6 : Tracé du graphique permettant de visualiser la trajectoire du satellite, les vecteurs accélération et
# force gravitationnelle
plt.figure("Vecteurs acceleration et fg d'un satellite de la Terre", figsize=(10, 10))
plt.plot(x, y, "+", label="y=f(x)")
plt.xlabel("x en m")
plt.ylabel("y en m")
plt.xlim(-50000000, 50000000) # extrémités des échelles sur x et y
plt.ylim(-50000000, 50000000)
plt.title(
"Mouvement d'un satellite géostationnaire autour de la Terre \nComparaison des vecteurs accélération et force "
"gravitationnelle")
for k in range(len(ax)):
plt.arrow(x[k], y[k], 50000000 * ax[k], 50000000 * ay[k], facecolor="b", edgecolor="b", width=200000,
head_width=1000000, length_includes_head=True) # Tracé du vecteur accélération
plt.arrow(x[k], y[k], 20000 * Fx[k], 20000 * Fy[k], facecolor="r", edgecolor="r", width=200000, head_width=1000000,
length_includes_head=True) # Tracé du vecteur force gravitationnelle
plt.show()
I'm trying to build a notebook for beginners as me, to plot the Google Gata Mobility Report, but I'm having trouble adjusting on a single image all the plots and save them on a single file. What can I do to get that output?
Here's the original code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
plt.style.use('seaborn-poster')
warnings.filterwarnings('ignore')
gmr_df = pd.read_csv ('https://www.gstatic.com/covid19/mobility/Global_Mobility_Report.csv')
# Categorías disponibles en el reporte de Movilidad de Google.
categories_google_mobility = ['retail_and_recreation_percent_change_from_baseline',
'grocery_and_pharmacy_percent_change_from_baseline',
'parks_percent_change_from_baseline',
'transit_stations_percent_change_from_baseline',
'workplaces_percent_change_from_baseline',
'residential_percent_change_from_baseline']
categories_google_mobility
# Selecciona el país y la región.
country = 'Mexico'
region = 'Colima'
sub_df = gmr_df[(gmr_df['country_region']== country) & (gmr_df['sub_region_1']==region)]
sub_df.loc[:,'date'] = pd.to_datetime(sub_df.loc[:,'date'])
sub_df = sub_df.sort_values('date', ascending=True)
# Con esto puedes comenzar a visualizar las series de tiempo del reporte de Google
for group in categories_google_mobility:
print(group)
fig, ax = plt.subplots(figsize=(16, 4))
plt.plot(sub_df['date'], sub_df[group], label=group)
#La siguiente línea, dibuja una línea horizontal con el valor base (0).
ax.axhline(y=0, color='gray')
#Las siguientes dos líneas de código (ax.axvline) son contextuales. En este caso, la primera marcará una línea vertical color rojo en el 18 de marzo; corresponde a la Declaratoria de Emergencia en el estado de Colima. La segunda, con fecha del primero de junio, alude al inicio de la Nueva Normalidad en el país.
ax.axvline(pd.to_datetime('2020-03-18'), color='r', linestyle='--', lw=2)
ax.axvline(pd.to_datetime('2020-06-01'), color='g', linestyle='--', lw=2)
plt.title(country + ' '+ region + ': ' + group)
plt.tight_layout()
plt.grid()
plt.show()
Is this what you're looking for? If so, you were very close. The subplots command allows you to set a grid of axes within the figure that are contained in a numpy array. Then instead of plt.plot you use ax.plot, and so forth for setting properties.
# Con esto puedes comenzar a visualizar las series de tiempo del reporte de Google
n = len(categories_google_mobility)
fig, axes = plt.subplots(n, 1, figsize=(16, 4 * n))
for group, ax in zip(categories_google_mobility, axes):
print(group)
ax.plot(sub_df['date'], sub_df[group], label=group)
#La siguiente línea, dibuja una línea horizontal con el valor base (0).
ax.axhline(y=0, color='gray')
#Las siguientes dos líneas de código (ax.axvline) son contextuales. En este caso, la primera marcará una línea vertical color rojo en el 18 de marzo; corresponde a la Declaratoria de Emergencia en el estado de Colima. La segunda, con fecha del primero de junio, alude al inicio de la Nueva Normalidad en el país.
ax.axvline(pd.to_datetime('2020-03-18'), color='r', linestyle='--', lw=2)
ax.axvline(pd.to_datetime('2020-06-01'), color='g', linestyle='--', lw=2)
ax.set_title(country + ' '+ region + ': ' + group)
ax.grid(True)
fig.tight_layout()
fig.savefig("plot.png")
I actually work on a real time graphic equalizer on python. I'm using pyaudio module, scipy, numpy. My equalizer is based on a third octave band filter bank from 25 Hz to 20 kHz (so 30 bands). This filter bank divides an input signal into 30 filtered signals (centered on the center frequency of each third octave band). Also, the streaming is implemented block by block (using pyaudio and callback method).
I used filtfilt from scipy.signal module but I had some discontinuities between each block (some audible click). So, I've followed Continuity issue when applying an IIR filter on successive time-frames and it works well for high frequencies.
But for low frequencies I need to follow these the steps :
1) downsampling input signal (to keep a good definition's filter);
2) filtering with lfilter_zi to keep continuity between each block (for streaming);
3) upsampling the filtered signal.
My problem is the upsampling because that breaks the continuity between each block (see figure below)
Discontinuities between 2 blocks when downsampling and upsampling a signal (sinus at 1000Hz here)
Also, here is my code of third octave band filter bank :
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 16:14:09 2019
#author: William
"""
from __future__ import division
import numpy as np
import scipy.signal as sc
def oct3_dsgn(fc, fs, type_filt='cheby2_bandpass', output='ba'):
"""
Calcul les coefficients B et A d'un filtre passe-bande pour chacune des
bandes de tiers d'octave entre 25 Hz et 20 kHz.
La fonction cheb2ord permet d'optimiser l'ordre et la bande passante du
filtre en fonction des fréquences de coupures et de leurs gains respectifs
(gpass, gstop) et de la fréquence d'échantillonnage.
"""
#------- Définition des fréquences inférieures et supérieures de la bande n
fc1 = fc / 2**(1/6)
fc2 = fc * 2**(1/6)
#------- Définition des fréquences centrales des bandes n-1 et n+1
fm1 = fc1 / 2**(1/6)
fm2 = fc2 * 2**(1/6)
#------- Définition des fréquences normalisées par rapport à f_nyquist
W1 = fc1/(fs/2)
W2 = fc2/(fs/2)
Wm1 = fm1/(fs/2)
Wm2 = fm2/(fs/2)
#------- Définition des filtres passe-bande, passe-bas et passe-haut
if type_filt == 'cheby2_bandpass':
gpass = 20*np.log10(np.sqrt(2)) # Équivalent à 3dB
gstop = 45
n_filt, Wn = sc.cheb2ord([W1, W2], [Wm1, Wm2], gpass, gstop)
if output=='ba':
B, A = sc.cheby2(n_filt, gstop, Wn, btype='band', output='ba')
elif output=='sos':
sos = sc.cheby2(n_filt, gstop, Wn, btype='band', output='sos')
elif type_filt == 'butter':
gpass = 20*np.log10(np.sqrt(2)) # Équivalent à 3dB
gstop = 30
n_filt, Wn = sc.buttord([W1, W2], [Wm1, Wm2], gpass, gstop)
if output=='ba':
B, A = sc.butter(n_filt, Wn, btype='band', output='ba')
elif output=='sos':
sos = sc.cheby2(n_filt, gstop, Wn, btype='band', output='sos')
elif type_filt == 'cheby2_low':
gpass = 20*np.log10(np.sqrt(2)) # Équivalent à 3dB
gstop = 45
n_filt, Wn = sc.cheb2ord(W2, Wm2, gpass, gstop)
if output=='ba':
B, A = sc.cheby2(n_filt, gstop, Wn, btype='low', output='ba')
elif output=='sos':
sos = sc.cheby2(n_filt, gstop, Wn, btype='low', output='sos')
elif type_filt == 'cheby2_high':
gpass = 20*np.log10(np.sqrt(2)) # Équivalent à 3dB
gstop = 45
n_filt, Wn = sc.cheb2ord(W1, Wm1, gpass, gstop)
if output=='ba':
B, A = sc.cheby2(n_filt, gstop, Wn, btype='high', output='ba')
elif output=='sos':
sos = sc.cheby2(n_filt, gstop, Wn, btype='high', output='sos')
if output == 'ba':
return B, A
elif output == 'sos':
return sos
def oct3_filter(signal, fs, gain_general = 0, gain_bande = np.zeros((30, )), plot=False):
"""
Calcul le signal filtré à partir du signal initial grâce une reconstruction
parfaite bande par bande. Le signal initial est filtré pour chacune des bandes.
Lorsque les fréquences sont trop basses, un sous-échantillonnage est opéré
pour gagner en résolution fréquentielle et en bande passante.
Pour la bande à 25 Hz, un filtre passe-bas est utilisé. La bande à 25 Hz
comprend donc toutes les fréquences inférieures ou égales à 25 Hz.
De même, pour la bande à 20 kHz un filtre passe-haut est utlisé. La bande à
20 kHz comprend donc toutes les fréquences au-dessus de 18 kHz.
"""
#------- Définition des fréquences centrales exactes en base 2
fc_oct3 = (1000) * (2**(1/3))**np.arange(-16, 14)
n_bande = len(fc_oct3)
n_signal = len(signal)
#------- Définition des matrices de stockage des signaux et des gains
signal_filt = np.zeros((n_signal, n_bande))
Gain = 10**(gain_bande/20)
#------- Affichage de la réponse des filtres 1/3 d'octaves
if plot == True:
import matplotlib.pyplot as plt
plt.figure(0, figsize=(10,5))
#------- Boucle sur les bandes de 10 Hz à 20 kHz
for ii in range(0, n_bande):
if ii == n_bande-1 :
## bande à 20 kHz
sos = oct3_dsgn(fc_oct3[ii], fs, type_filt='cheby2_high', output='sos')
signal_filt[:, ii] = Gain[ii] * sc.sosfilt(sos, signal)
## affichage de la réponse du filtre
if plot == True:
w, h = sc.freqz(sos)
plt.semilogx(w/2/np.pi*fs, 20*np.log10(abs(h)), 'k')
elif ii == 0 :
## bande à 25 Hz
n_decimate = 32
x = sc.decimate(signal, n_decimate)
sos = oct3_dsgn(fc_oct3[ii], fs//n_decimate, type_filt='cheby2_low', output='sos')
x = sc.sosfilt(sos, x)
signal_filt[:, ii] = Gain[ii] * sc.resample(x, n_signal)
## affichage de la réponse du filtre
if plot == True:
w, h = sc.freqz(sos)
plt.semilogx(w/2/np.pi*(fs//n_decimate), 20*np.log10(abs(h)), 'k')
elif n_bande-5 <= ii < n_bande-1:
## de 8 kHz à 16 kHz
sos = oct3_dsgn(fc_oct3[ii], fs, output='sos')
signal_filt[:, ii] = Gain[ii] * sc.sosfilt(sos, signal)
## affichage de la réponse du filtre
if plot == True:
w, h = sc.freqz(sos)
plt.semilogx(w/2/np.pi*fs, 20*np.log10(abs(h)), 'k')
elif n_bande-10 <= ii < n_bande-5:
## de 2,5 kHz à 6,3 kHz
n_decimate = 2
x = sc.decimate(signal, n_decimate)
sos = oct3_dsgn(fc_oct3[ii], fs//n_decimate, output='sos')
x = sc.sosfilt(sos, x)
signal_filt[:, ii] = Gain[ii] * sc.resample(x, n_signal)
## affichage de la réponse du filtre
if plot == True:
w, h = sc.freqz(sos)
plt.semilogx(w/2/np.pi*(fs//n_decimate), 20*np.log10(abs(h)), 'k')
elif n_bande-15 <= ii < n_bande-10:
## de 800 Hz à 2 kHz
n_decimate = 4#round(fs/(2*fmax))-1
x = sc.decimate(signal, n_decimate)
sos = oct3_dsgn(fc_oct3[ii], fs//n_decimate, output='sos')
x = sc.sosfilt(sos, x)
signal_filt[:, ii] = Gain[ii] * sc.resample(x, n_signal)
## affichage de la réponse du filtre
if plot == True:
w, h = sc.freqz(sos)
plt.semilogx(w/2/np.pi*(fs//n_decimate), 20*np.log10(abs(h)), 'k')
elif n_bande-20 <= ii < n_bande-15:
## de 250 Hz à 630 Hz
n_decimate = 8#round(fs/(2*fmax))-1
x = sc.decimate(signal, n_decimate)
sos = oct3_dsgn(fc_oct3[ii], fs//n_decimate, output='sos')
x = sc.sosfilt(sos, x)
signal_filt[:, ii] = Gain[ii] * sc.resample(x, n_signal)
### affichage de la réponse du filtre
if plot == True:
w, h = sc.freqz(sos)
plt.semilogx(w/2/np.pi*(fs//n_decimate), 20*np.log10(abs(h)), 'k')
elif n_bande-25 <= ii < n_bande-20:
## de 80 Hz à 200 Hz
n_decimate = 16#round(fs/(2*fmax))-1
x = sc.decimate(signal, n_decimate)
sos = oct3_dsgn(fc_oct3[ii], fs//n_decimate, output='sos')
x = sc.sosfilt(sos, x)
signal_filt[:, ii] = Gain[ii] * sc.resample(x, n_signal)
## affichage de la réponse du filtre
if plot == True:
w, h = sc.freqz(sos)
plt.semilogx(w/2/np.pi*(fs//n_decimate), 20*np.log10(abs(h)), 'k')
elif n_bande-29 <= ii < n_bande-25:
## de 25 Hz à 63 Hz
n_decimate = 32#round(fs/(2*fmax))-1
x = sc.decimate(signal, n_decimate)
sos = oct3_dsgn(fc_oct3[ii], fs//n_decimate, output='sos')
x = sc.sosfilt(sos, x)
signal_filt[:, ii] = Gain[ii] * sc.resample(x, n_signal)
## affichage de la réponse du filtre
if plot == True:
w, h = sc.freqz(sos)
plt.semilogx(w/2/np.pi*(fs//n_decimate), 20*np.log10(abs(h)), 'k')
if plot == True:
plt.grid(which='both', linestyle='-', color='grey')
# plt.xticks([20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000],
# ["20", "50", "100", "200", "500", "1K",
# "2K", "5K", "10K", "20K"])
plt.xlabel('Fréquence [Hz]'), plt.ylabel('Gain [dB]')
plt.title('Réponse en fréquence des filtres 1/3 d\'octaves')
plt.xlim((10, 22e3)), plt.ylim((-5, 1))
plt.show()
#------- Sommation des signaux filtrés pour recomposer le signal d'origine
S = signal_filt.sum(axis=1)
S = S - np.mean(S)
## tuckey_window = sc.tukey(len(S), alpha=0.01)
## S = tuckey_window * S
G = 10**(gain_general/20)
return G * S
l have two columns that represent : right sequence and predicted sequence. l want to make statistics on the number of deletion, substitution and insertion by comparing each right sequence with its predicted sequence.
l did the levenstein distance to get the number of characters which are different (see the function below) and error_dist function to get the most common errors (in terms of substitution) :
here is a sample of my data :
de de
date date
pour pour
etoblissemenls etablissements
avec avec
code code
communications communications
r r
seiche seiche
titre titre
publiques publiques
ht ht
bain bain
du du
ets ets
premier premier
dans dans
snupape soupape
minimum minimum
blanc blanc
fr fr
nos nos
au au
bl bl
consommations consommations
somme somme
euro euro
votre votre
offre offre
forestier forestier
cs cs
de de
pour pour
de de
paye r
cette cette
votre votre
valeurs valeurs
des des
gfda gfda
tva tva
pouvoirs pouvoirs
de de
revenus revenus
offre offre
ht ht
card card
noe noe
montant montant
r r
comprises comprises
quantite quantite
nature nature
ticket ticket
ou ou
rapide rapide
de de
sous sous
identification identification
du du
document document
suicide suicide
bretagne bretagne
tribunal tribunal
services services
cif cif
moyen moyen
gaec gaec
total total
lorsque lorsque
contact contact
fermeture fermeture
la la
route route
tva tva
ia ia
noyal noyal
brie brie
de de
nanterre nanterre
charcutier charcutier
semestre semestre
de de
rue rue
le le
bancaire bancaire
martigne martigne
recouvrement recouvrement
la la
sainteny sainteny
de de
franc franc
rm rm
vro vro
here is my code
import pandas as pd
import collections
import numpy as np
import matplotlib.pyplot as plt
import distance
def error_dist():
df = pd.read_csv('data.csv', sep=',')
df = df.astype(str)
df = df.replace(['é', 'è', 'È', 'É'], 'e', regex=True)
df = df.replace(['à', 'â', 'Â'], 'a', regex=True)
dictionnary = []
for i in range(len(df)):
if df.manual_raw_value[i] != df.raw_value[i]:
text = df.manual_raw_value[i]
text2 = df.raw_value[i]
x = len(df.manual_raw_value[i])
y = len(df.raw_value[i])
z = min(x, y)
for t in range(z):
if text[t] != text2[t]:
d = (text[t], text2[t])
dictionnary.append(d)
#print(dictionnary)
dictionnary_new = dict(collections.Counter(dictionnary).most_common(25))
pos = np.arange(len(dictionnary_new.keys()))
width = 1.0
ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(dictionnary_new.keys())
plt.bar(range(len(dictionnary_new)), dictionnary_new.values(), width, color='g')
plt.show()
enter image description here
and the levenstein distance :
def levenstein_dist():
df = pd.read_csv('data.csv', sep=',')
df=df.astype(str)
df['string diff'] = df.apply(lambda x: distance.levenshtein(x['raw_value'], x['manual_raw_value']), axis=1)
plt.hist(df['string diff'])
plt.show()
enter image description here
Now l want to make a histograms showing three bins : number of substitution, number of insertion and number of deletion . How can l proceed ?
Thank you
Thanks to the suggestions of #YohanesGultom the answer for the problem can be found here :
http://www.nltk.org/_modules/nltk/metrics/distance.html
or
https://gist.github.com/kylebgorman/1081951
I'm touching the goal of my project, but I'm getting a problem on : How I can create a completeness map ?
I have lots of data, a field with maybe 500.000 objects which are represented by dots in my plot with different zoom :
I would like to create a mask, I mean, cut my plot in tiny pixels, and say if I have an object in this pixel, I get the value : 1 (black for example) elif, I have not object in my pixel, I get the value : 0 (white for example).
I'll create a mask and I could divide each field by this mask.
The problem is that I don't know how I can process in order to make that :/
I create a first script in order to get a selection on my data. This one :
#!/usr/bin/python
# coding: utf-8
from astropy.io import fits
from astropy.table import Table
import numpy as np
import matplotlib.pyplot as plt
###################################
# Fichier contenant le champ brut #
###################################
filename = '/home/valentin/Desktop/Field52_combined_final_roughcal.fits'
# Ouverture du fichier à l'aide d'astropy
field = fits.open(filename)
print "Ouverture du fichier : " + str(filename)
# Lecture des données fits
tbdata = field[1].data
print "Lecture des données du fits"
###############################
# Application du tri sur PROB #
###############################
mask = np.bitwise_and(tbdata['PROB'] < 1.1, tbdata['PROB'] > -0.1)
new_tbdata = tbdata[mask]
print "Création du Masque"
#################################################
# Détermination des valeurs extremales du champ #
#################################################
# Détermination de RA_max et RA_min
RA_max = np.max(new_tbdata['RA'])
RA_min = np.min(new_tbdata['RA'])
print "RA_max vaut : " + str(RA_max)
print "RA_min vaut : " + str(RA_min)
# Détermination de DEC_max et DEC_min
DEC_max = np.max(new_tbdata['DEC'])
DEC_min = np.min(new_tbdata['DEC'])
print "DEC_max vaut : " + str(DEC_max)
print "DEC_min vaut : " + str(DEC_min)
#########################################
# Calcul de la valeur centrale du champ #
#########################################
# Détermination de RA_moyen et DEC_moyen
RA_central = (RA_max + RA_min)/2.
DEC_central = (DEC_max + DEC_min)/2.
print "RA_central vaut : " + str(RA_central)
print "DEC_central vaut : " + str(DEC_central)
print " "
print " ------------------------------- "
print " "
##############################
# Détermination de X et de Y #
##############################
# Creation du tableau
new_col_data_X = array = (new_tbdata['RA'] - RA_central) * np.cos(DEC_central)
new_col_data_Y = array = new_tbdata['DEC'] - DEC_central
print 'Création du tableau'
# Creation des nouvelles colonnes
col_X = fits.Column(name='X', format='D', array=new_col_data_X)
col_Y = fits.Column(name='Y', format='D', array=new_col_data_Y)
print 'Création des nouvelles colonnes X et Y'
# Creation de la nouvelle table
tbdata_final = fits.BinTableHDU.from_columns(new_tbdata.columns + col_X + col_Y)
# Ecriture du fichier de sortie .fits
tbdata_final.writeto('{}_{}'.format(filename,'mask'))
print 'Ecriture du nouveau fichier mask'
field.close()
Ok, it's working ! But now, the second part is this to the moment :
###################################################
###################################################
###################################################
filename = '/home/valentin/Desktop/Field52_combined_final_roughcal.fits_mask'
print 'Fichier en cours de traitement' + str(filename) + '\n'
# Ouverture du fichier à l'aide d'astropy
field = fits.open(filename)
# Lecture des données fits
tbdata = field[1].data
figure = plt.figure(1)
plt.plot (tbdata['X'], tbdata['Y'], '.')
plt.show()
Do you have any idea how process ?
How I can cut my plot in tiny bin ?
Thank you !
UPDATE :
After the answer from armatita, I updated my script :
###################################################
###################################################
###################################################
filename = '/home/valentin/Desktop/Field52_combined_final_roughcal.fits_mask'
print 'Fichier en cours de traitement' + str(filename) + '\n'
# Opening file with astropy
field = fits.open(filename)
# fits data reading
tbdata = field[1].data
##### BUILDING A GRID FOR THE DATA ########
nodesx,nodesy = 360,360 # PIXELS IN X, PIXELS IN Y
firstx,firsty = np.min(tbdata['X']),np.min(tbdata['Y'])
sizex = (np.max(tbdata['X'])-np.min(tbdata['X']))/nodesx
sizey = (np.max(tbdata['Y'])-np.min(tbdata['Y']))/nodesy
grid = np.zeros((nodesx+1,nodesy+1),dtype='bool') # PLUS 1 TO ENSURE ALL DATA IS INSIDE GRID
# CALCULATING GRID COORDINATES OF DATA
indx = np.int_((tbdata['X']-firstx)/sizex)
indy = np.int_((tbdata['Y']-firsty)/sizey)
grid[indx,indy] = True # WHERE DATA EXISTS SET TRUE
# PLOT MY FINAL IMAGE
plt.imshow(grid.T,origin='lower',cmap='binary',interpolation='nearest')
plt.show()
I find this plot :
So, when I play with the bin size, I can see more or less blank which indicate object or not in my pixel :)
This is usually a process of inserting your data into a grid (pixel wise, or node wise). The following example builds a grid (2D array) and calculates the "grid coordinates" for the sample data. Once it has those grid coordinates (which in true are nothing but array indexes) you can just set those elements to True. Check the following example:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.normal(0,1,1000)
y = np.random.normal(0,1,1000)
##### BUILDING A GRID FOR THE DATA ########
nodesx,nodesy = 100,100 # PIXELS IN X, PIXELS IN Y
firstx,firsty = x.min(),y.min()
sizex = (x.max()-x.min())/nodesx
sizey = (y.max()-y.min())/nodesy
grid = np.zeros((nodesx+1,nodesy+1),dtype='bool') # PLUS 1 TO ENSURE ALL DATA IS INSIDE GRID
# CALCULATING GRID COORDINATES OF DATA
indx = np.int_((x-firstx)/sizex)
indy = np.int_((y-firsty)/sizey)
grid[indx,indy] = True # WHERE DATA EXISTS SET TRUE
# PLOT MY FINAL IMAGE
plt.imshow(grid.T,origin='lower',cmap='binary',interpolation='nearest')
plt.show()
, which results in:
Notice I'm showing an image with imshow. Should I decrease the number of pixels (20,20 = nodesx, nodesy) I get:
Also for a more automatic plot in matplotlib you can consider hexbin.