I want to plot a waveform from two black-hole mergersI have a .h5 file that I got from a public waveform catalog. I I am kind of a beginner with using python so I don't really know what to do in this situation. I have a .h5 file that has a .dat file inside that I want to use to make a plot. I got the file from a public waveform catalog at:
http://www.black-holes.org/waveforms/data/DisplayDownloadPage.php/?id=SXS:BBH:0001#
the name of the file is :
rhOverM_Asymptotic_GeometricUnits.h5
it is in the Lev5 directory. The contents of the .h5 file are described in:
https://www.black-holes.org/waveforms/docs.html
There is a dataset in the file that I think describes the waveform that I want to plot. The problem is that I don't know how to get into the data set. I have gotten as far as doing:
import numpy as np
import h5py
from pylab import plot,show
f = h5.py.File("rhOverM_Asymptotic_GeometricUnits.h5","r")
ks = f.keys()
From here I don't know how to create the x and y axis that would go into the plot function. I am assuming that I need another attribute that belongs to the h5py module, but I am not even sure if I am using the right terminology. Any help would be appreciated.
Try this:
import matplotlib.pyplot as plt
import h5py
f = h5py.File("rhOverM_Asymptotic_GeometricUnits.h5", "r")
data = f['Extrapolated_N2.dir/Y_l2_m-1.dat']
plt.plot(data[:, 0], data[:, 1], label='column1')
plt.plot(data[:, 0], data[:, 2], label='column2')
plt.legend()
plt.show()
Related
I'm working on a project and I want to work with networkx package.
The file that has the adjacency matrix of the graph is of .npy format. So first I want to load it by numpy and then I want to do some graph functions on it by networkx.
I wrote this code to get info about my graph but this is wrong. I searched for networkx functions but I'm confused witch function can I use for a .npy file?
anybody can help me to get the info of the graph that I loaded by numpy??
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
total = np.load('totaldata.npy')
G = nx.from_numpy_matrix(total)
print (nx.info(G))
when I run the code I get this error:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/networkx/convert_matrix.py",
line 550, in from_numpy_matrix
n, m = A.shape
ValueError: too many values to unpack (expected 2)
I'm new to Python and there is a piece of Python coding that I am having trouble getting to graph.
Specifically how to parse data from an Excel spreadsheet in order to generate and plot some basic value comparison graphs.
I'm using the Spyder IDE with Python 3.6.3.
The file 'foc' location is:
C:\Users\Murphy\Desktop\WinPython-64bit-3.6.3.0Qt5\PYWorkFiles\foc.csv
I have more than one version of the excel spreadsheet foc file as I have attempted to graph it in more than one format. The two formats it is stored in at present are csv and xlsx
The code scraps I have put together at present are:
import xlrd
workbook = xlrd.open_workbook('foc.xlsx')
from csv import reader
import matplotlib.pyplot as plt
with open('foc.csv', 'r') as f:
data = list(reader(f))
taste = [i[6] for i in data]
plt.plot(range(len(taste)), taste)
plt.show()
plt.plot()
All these pieces of code generate is two useless graphs (I've attached them below) with only the first one even showing any of the foc spreadsheet data.
Can I get any help with this? I have very little knowledge of how to use Python.
graph1
graph2
To make it as simple as possible, I recommend using numpy(pip install numpy to install it). Using numpy we can do this:
import matplotlib.pyplot as plt
import numpy as np
x, y = np.loadtxt('foc.csv', delimiter=',', unpack=True)
plt.plot(x,y, label='Loaded from file!')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Test')
plt.legend()
plt.show()
and this is our result
foc.csv:
1, 10
2, 20
3, 30
4, 40
5, 50
If you still need more help or want to get into more complex things using matplotlib, I recommend checking out sentdex's tutorials
I have a set of dicom images(contains 160 .dcm files). I can visualize a single file by the following python code:
import pydicom as dicom
import os
import numpy
import matplotlib.pyplot as plt
filename = "./myfiles/MR000130.dcm";
dataset = dicom.dcmread(filename)
plt.imshow(dataset.pixel_array, cmap=plt.cm.bone)
plt.show()
My question is:
How do I visualize these whole bunch of volumetric data as a single picture?
Is there any way to obtain the z-buffer information?
It's in the file. There is stuff in the DICOM apart from pixel data. See it with
print(dataset._pretty_str).
It might be dataset.SliceLocation.
We can't tell you how to change 3D to 2D. You could read all the slices, and then reslice in other planes. You could do some fancy segmentation and render surfaces in 3D. You need to decide what is most appropriate for your case.
This seems like it's going to be something simple that will fix my code but I think I've just looked at the code too much at the moment and need to get some fresh eyes on it. I'm simply trying to bring in a Grib2 file that I've downloaded from NCEP for the HRRR model. According to their information the grid type is Lambert Conformal with the extents of (21.13812, 21.14055, 47.84219, 47.83862) for the latitudes of the corners and (-122.7195, -72.28972, -60.91719, -134.0955) for the longitudes of the corners for the models domain.
Before even trying to zoom into my area of interest I just wanted to simply display an image in the appropriate CRS however when I try to do this for the domain of the model I get the borders and coastlines to fall within that extent but the actual image produced from the Grib2 file is just zoomed into. I've tried to use extent=[my domain extent] but it always seems to crash the notebook I'm testing it in. Here is my code and the associated image that I get from it.
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy
from mpl_toolkits.basemap import Basemap
from osgeo import gdal
gdal.SetConfigOption('GRIB_NORMALIZE_UNITS', 'NO')
plt.figure()
filename='C:\\Users\\Public\\Documents\\GRIB\\hrrr.t18z.wrfsfcf00.grib2'
grib = gdal.Open(filename, gdal.GA_ReadOnly)
z00 = grib.GetRasterBand(47)
meta00 = z00.GetMetadata()
band_description = z00.GetDescription()
bz00 = z00.ReadAsArray()
latitude_south = 21.13812 #38.5
latitude_north = 47.84219 #50
longitude_west = -134.0955 #-91
longitude_east = -60.91719 #-69
fig = plt.figure(figsize=(20, 20))
title= meta00['GRIB_COMMENT']+' at '+meta00['GRIB_SHORT_NAME']
fig.set_facecolor('white')
ax = plt.axes(projection=ccrs.LambertConformal())
ax.add_feature(cartopy.feature.BORDERS, linestyle=':')
ax.coastlines(resolution='110m')
ax.imshow(bz00,origin='upper',transform=ccrs.LambertConformal())
plt.title(title)
plt.show()
Returns Just Grib File
If I change:
ax = plt.axes(projection=ccrs.LambertConformal()
to
ax = plt.axes(projection=ccrs.LambertConformal(central_longitude=-95.5,
central_latitude=38.5,cutoff=21.13)
I get my borders but my actual data is not aligned and it creates what I'm dubbing a Batman plot.
Batman Plot
A similar issue occurs even when I do zoom into the domain and still have my borders present. The underlying data from the Grib file doesn't change to correspond to what I'm trying to get.
So as I've already said this is probably something that is an easy fix that I'm just missing but if not, it would be nice to know what step or what process I'm screwing up that I can learn from so that I don't do it in the future!
Updated 1:
I've added and changed some code and am back to getting only the image to show without the borders and coastlines showing up.
test_extent = [longitude_west,longitude_east,latitude_south,latitude_north]
ax.imshow(bz00,origin='upper',extent=test_extent)
This gives me the following image.
Looks exactly like image 1.
The other thing that I'm noticing which maybe the root cause of all of this is that when I'm printing out the value for plt.gca().get_ylim() and plt.gca().get_xlim() I'm getting hugely different values depending on what is being displayed.
It seems that my problem arises from the fact that the Grib file regardless of whether or not it can be displayed properly in other programs just doesn't play nicely with Matplotlib and Cartopy out of the box. Or at the very least does not with the Grib files that I was using. Which for sake of this perhaps helping others in the future are from the NCEP HRRR model that you can get here or here.
Everything seems to work nicely if you convert the file from Grib2 format to NetCDF format and I was able to get what I wanted with the borders, coastlines, etc. on the map. I've attached the code and the output below to show how it worked. Also I hand picked a single dataset that I wanted to display to test versus my previous code so incase you want to look at the rest of datasets available in the file you'll need to utilize ncdump or something similar to view the information on the datasets.
import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy
import cartopy.feature as cfeature
from osgeo import gdal
gdal.SetConfigOption('GRIB_NORMALIZE_UNITS', 'NO')
nc_f = 'C:\\Users\\Public\\Documents\\GRIB\\test.nc' # Your filename
nc_fid = Dataset(nc_f, 'r') # Dataset is the class behavior to open the
# file and create an instance of the ncCDF4
# class
# Extract data from NetCDF file
lats = nc_fid.variables['gridlat_0'][:]
lons = nc_fid.variables['gridlon_0'][:]
temp = nc_fid.variables['TMP_P0_L1_GLC0'][:]
fig = plt.figure(figsize=(20, 20))
states_provinces = cfeature.NaturalEarthFeature(category='cultural', \
name='admin_1_states_provinces_lines',scale='50m', facecolor='none')
proj = ccrs.LambertConformal()
ax = plt.axes(projection=proj)
plt.pcolormesh(lons, lats, temp, transform=ccrs.PlateCarree(),
cmap='RdYlBu_r', zorder=1)
ax.add_feature(cartopy.feature.BORDERS, linestyle=':', zorder=2)
ax.add_feature(states_provinces, edgecolor='black')
ax.coastlines()
plt.show()
Final Preview of Map
I am learning Python and I have a side project to learn to display data using matplotlib.pyplot module. Here is an example to display the data using dates[] and prices[] as data. Does anyone know why we need line 5 and line 6? I am confused why this step is needed to have the graph displayed.
from sklearn import linear_model
import matplotlib.pyplot as plt
def showgraph(dates, prices):
dates = numpy.reshape(dates, (len(dates), 1)) # line 5
prices = numpy.reshape(prices, (len(prices), 1)) # line 6
linear_mod = linear_model.LinearRegression()
linear_mod.fit(dates,prices)
plt.scatter(dates,prices,color='yellow')
plt.plot(dates,linear_mod.predict(dates),color='green')
plt.show()
try the following in terminal to check the backend:
import matplotlib
import matplotlib.pyplot
print matplotlib.backends.backend
If it shows 'agg', it is a non-interactive one and wont show but plt.savefig works.
To show the plot, you need to switch to TkAgg or Qt4Agg.
You need to edit the backend in matplotlibrc file. To print its location in terminal do the following.
import matplotlib
matplotlib.matplotlib_fname()
more about matplotlibrc
Line 5 and 6 transform what Im assuming are row vectors (im not sure how data and prices are encoded before this transformation) into column vectors. So now you have vectors that look like this.
[0,
1,
2,
3]
which is the form that linear_model.Linear_Regression.fit() is expecting. The reshaping was not necessary for plotting under the assumption that data and prices are row vectors.
My approach is exactly like yours but still without line 5 and 6 display is correct. I think those line are unnecessary. It seems that you do not need fit() function because of your input data are in row format.