I'm trying to animate some quivers on a basemap using Numpy, but the data is on differents files (E and N gps displacements). In first place, I try to load all the files with np.loadtxt and glob, and the result it's an array (or matrix, at this point I don't know) of this style:
bla = [array([1,2,3,....,1000]), array([1,2,3,....,1000]),....]
What I want, is to animate quivers of the displacement of the gps data in a basemap, for that I made this code:
import numpy as np
from glob import glob
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import matplotlib.animation as animation
estaE = glob('/Users/joaquinjulve/Documents/Universidad/Herramientas/Examen/GPS_E/*e.out')
gpsE = [np.loadtxt(a) for a in estaE]
estaN = glob('/Users/joaquinjulve/Documents/Universidad/Herramientas/Examen/GPS_N/*n.out')
gpsN = [np.loadtxt(b) for b in estaN]
estaciones = np.loadtxt('/Users/joaquinjulve/Documents/Universidad/Herramientas/Examen/estaciones.coord.out', usecols=(1,2))
gpsupE = np.asarray(gpsE)
gpsupN = np.asarray(gpsN)
desE = [a.T[1] for a in gpsE]
desN = [b.T[1] for b in gpsN]
t = [c.T[0]for c in gpsE]
tup = np.asarray(t)
desupE = np.asarray(desE)
desupN = np.asarray(desN)
map = Basemap(projection='merc',
llcrnrlat=-45, llcrnrlon=-75,
urcrnrlat=-25, urcrnrlon=-60, resolution=None)
map.drawparallels(np.arange(-90,90.,4), labels=[1,0,0,0])
map.drawmeridians(np.arange(-180,180,4), labels=[0,0,0,1])
map.bluemarble(scale=4)
lat = estaciones.T[0]
lon = estaciones.T[1]
x, y = map(lon, lat)
Q = map.quiver(x, y, desupE, desupN, color='red')
def update_quiver(Q, x, y):
U = desupE
V = desupN
Q.set_UVC(U,V)
anim = animation.FuncAnimation(map, update_quiver, fargs=(Q, x, y),
interval=10, blit=True)
plt.show()
Related
I am subplotting over a loop, but the output is really crappy. I think it's stacking each single yticks.
Image Output
I need to give the image a single y axis, that's why I'm saving y_max and y_min for each iteration.
import matplotlib.pyplot as plt
import scipy
from scipy.optimize import curve_fit
from matplotlib import rc
rc('text', usetex=True)
import numpy as np
import math
from ctypes import *
import sys
np.finfo(np.dtype("float64"))
correlation_elements = 5
y_mag_max = np.zeros(correlation_elements)
y_mag_min = np.zeros(correlation_elements)
for i in range (correlation_elements):
fig_correl = plt.figure("correlations")
fig_correl.suptitle('Correlations')
start = i
end = i+correlation_elements
energy_correl_array = np.linspace(start, end, correlation_elements)
ax_correl_1 = fig_correl.add_subplot(1, 1, 1)
correlation_x_axis = np.linspace(0, correlation_elements-1, correlation_elements)
ax_correl_1.plot(correlation_x_axis, energy_correl_array,'.', label=r'$beta$ = {val:}'.format(val=i))
y_mag_max[i] = np.max(energy_correl_array)
y_mag_min[i] = np.min(energy_correl_array)
#Plotting Correlations
fig_correl.legend()
y_max = np.max(y_mag_max)
y_min = np.min(y_mag_min)
ax_correl_1.set_ylim(y_min, y_max)
ax_correl_1.set_ylabel('Energy')
plt.show()
I have to create a pendulum simulation on plot. I have to read data from file, then only thing I have to solve is X and Y cords, what I did. It is specified that I am supposed to use "roll"/"pitch"/"yaw" columns and with one of them make a simulation.
There is the file: https://pastebin.com/D2Tt3tBj
Here is my code:
import pandas as pd
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from mpl_toolkits.mplot3d import Axes3D
from tkinter import ttk
from tkinter import scrolledtext
import numpy as np
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation
pd.set_option('display.max_rows', None) # wyswietla caly plik
def odrzuc_n(df_full, n):
df_full = df_full.iloc[n:]
return df_full
def wczytaj_dane():
data = pd.read_csv("outputPendulum02.log", delim_whitespace=True)
data.columns = ["roll", "pitch", "yaw", "a_x", "a_y", "a_z", "m_x", "m_y", "m_z", "omega_x", "omega_y", "omega_z"]
data = data.drop(columns=["a_x", "a_y", "a_z", "m_x", "m_y", "m_z", "omega_x", "omega_y", "omega_z"])
data.index = [x for x in range(1, len(data.values) + 1)]
data.index.name = 'id'
df = pd.DataFrame(data)
seconds = []
x_cord = []
y_cord = []
which_angle = 'pitch'
for (index_label, row_series) in df.iterrows():
second = index_label * 0.04
seconds.append(second)
x = 50 * np.sin(row_series[which_angle])
y = 50 - 50 * np.cos(row_series[which_angle])
x_cord.append(x)
y_cord.append(y)
df['seconds'] = seconds
df['x_cord'] = x_cord
df['y_cord'] = y_cord
# print(df)
return df
df_full = wczytaj_dane()
how_many_to_delete = 500
df_full = odrzuc_n(df_full, how_many_to_delete)
data_cut = df_full
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')
def init(): # only required for blitting to give a clean slate.
ax.set_xlim(df_full['x_cord'].min()-5, df_full['x_cord'].max()+5)
ax.set_ylim(df_full['y_cord'].min()-5, df_full['y_cord'].max()+5)
return ln,
def update(frame):
xdata = (df_full.iloc[frame, 4])
ydata = (df_full.iloc[frame, 5])
ln.set_data(xdata, ydata)
if frame > 1225:
return 0
return ln,
ani = FuncAnimation(fig, update, frames=range(how_many_to_delete, 1225),
init_func=init, blit=True)
plt.show()
It's little messy... "odrzuc_n" function is function that drops N rows from dataframe. "Wczytaj_dane" is reading data from file. Columns of file are described in the code.
And finally my question. What's wrong with it? It shows an error at the end of animation. I don't really know is the X and Y determined properly. I have to make it in GUI that's why I have tkinter impoerted etc. But this part of code only generates plot.
I have a file with a table. I am trying to plot a velDisp vs. ABSMAG. Here is my code:
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.io.fits import getdata
from astropy.table import Table
data = getdata("Subset.fits")
data, hdr = getdata("Subset.fits",1,header = True)
table = fits.open('Subset.fits')
data1 = Table(table[1].data)
#print("Columnns:", data1[0].columns)
graph = Table.read('Subset.fits')
mag = data1['ABSMAG']
r_mag = mag[:,2]
x = graph['ABSMAG']
y = graph['velDisp']
plt.scatter(x, y, color = 'r')
plt.title('Velocity Dispersion vs Absolute Magnitude')
plt.xlabel('Abs Mag(r_band)')
plt.ylabel('Velocity Dispersion')
plt.grid()
plt.show()
It's giving me the error that x and y must be the same size.The velDisp I believe is in 3D so this may need to be done in log space. Any idea how to do this?
I'm working with a shapefile. I have no issues whatsoever reading it in, plotting it, and making the map pretty-looking. However, when I plot it (after reprojecting it to the correct EPSG using QGIS), the edges are all jagged (as shown below). Is there a way to smooth it using Python?
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import numpy as np
#insert code for basemap setup m = Basemap(...)
m.arcgisimage(service = 'ESRI_StreetMap_World_2D', xpixels = 1000, verbose = True)
states_info = m.readshapefile('shapefiles/states', 'states')
spc_info = m.readshapefile('shapefiles/corrected_epsg', 'spc', drawbounds = False)
patches = []
ax = plt.gca()
for info, shape in zip(m.spc_info, m.spc):
x, y = zip(*shape)
if info['DN'] == 2:
color = '#80c580'
zorder = 2
patches.append( Polygon(np.array(shape), True))
if info['DN'] == 5:
color = '#f7f780'
zorder = 3
patches.append( Polygon(np.array(shape), True))
ax.add_collection(PatchCollection(patches, facecolor= color, zorder=zorder, alpha = 0.7))
Source for these shapefiles.
This question's answers explain how the Shapely Package has a Simplify method based on the Douglas-Puecker algorithm.
Does anyone know why memory use keeps increasing? An idealised case is below, I can't see why.
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
Lon = np.linspace(-180,180,1440)
Lat = np.linspace(-90,90,721)
Lon,Lat = np.meshgrid(Lon,Lat)
m = Basemap()
X, Y = m(Lon, Lat)
matrix = np.random.rand(721,1440)
for i in range(0,100):
cs = m.contourf(X,Y,matrix)
plt.clf()
plt.close()
print i
May of been a memory leak - cannot replicate problem with the latest Matplotlib library.