Python SAC plot w/ grid - python

I'm required to use the information from a .sac file and plot it against a grid. I know that using various ObsPy functions one is able to plot the Seismograms using st.plot() but I can't seem to get it against a grid. I've also tried following the example given here "How do I draw a grid onto a plot in Python?" but have trouble when trying to configure my x axis to use UTCDatetime. I'm new to python and programming of this sort so any advice / help would be greatly appreciated.
Various resources used:
"http://docs.obspy.org/tutorial/code_snippets/reading_seismograms.html"
"http://docs.obspy.org/packages/autogen/obspy.core.stream.Stream.plot.html#obspy.core.stream.Stream.plot"

The Stream's plot() method actually automatically generates a grid, e.g. if you take the default example and plot it via:
from obspy.core import read
st = read() # without filename an example file is loaded
tr = st[0] # we will use only the first channel
tr.plot()
You may want to play with the number_of_ticks, tick_format and tick_rotationparameters as pointed out in http://docs.obspy.org/packages/autogen/obspy.core.stream.Stream.plot.html.
However if you want more control you can pass a matplotlib figure as input parameter to the plot() method:
from obspy.core import read
import matplotlib.pyplot as plt
fig = plt.figure()
st = read('/path/to/file.sac')
st.plot(fig=fig)
# at this point do whatever you want with your figure, e.g.
fig.gca().set_axis_off()
# finally display your figure
fig.show()
Hope it helps.

Related

Use loop for plotting, but plot only particular images from the plot

I have to use different csv files to create plots out of them in the same figure. My coding environment is google colab (it's like Jupyter notebook in google's cloud). So I decided to create a figure and then loop through the files and do the plots. It looks something like this:
import healpy as hp
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(16,12))
ax = fig.add_subplot(111)
for void_file in ['./filepath1.csv','./filepath2.csv','./filepath3.csv', ...]:
helper_image = hp.gnomview(void_file, .....)
data = func1(helper_image, .....)
plt.plot(len(data), data, ......)
What I want is to only add into the figure the plots created with the line plt.plot(len(data), data, ......), but what happens is that also the helper images from the line helper_image = hp.gnomview(....) sneak into the image and spoil it (healpy is a package for spherical data). The line helper_image = .... is only there to make some necessary calculations, but unfortunately they come along with plots.
How can I suppress the creation of the plots by helper_image = hp.gnomview(....)? Or can I somehow tell the figure or ax to include only plots that I specify? Or are there any easy alternatives that don't require a loop for plotting? Tnx
you can use return_projected_image=True and no_plot=True keyword arguments, see https://healpy.readthedocs.io/en/latest/generated/healpy.visufunc.gnomview.html

Interactive Ploting

I'm searching for an interactive pliting library. I have some dataset that I would like to plot like a scatter (if posible over an image), And need to show some information on focus (or click if focus it's not posible). Let's say for sake of the question, some number.
I don't really know if there a tool that would let me do this, without an excesive amount of code (probably I can do it myself using a canvas in tkinter).
I only have some experience in matplotlib for ploting. That's my principal limitation.
What I'm doing now is to annotate every marker with something like this:
import matplotlib.pyplot as plt
import numpy as np
x = [1,2,3,4,5]
y = [2,3,1,1,5]
an = [10,42,3,33,4]
plt.figure()
plt.plot(x,y,'o')
for i,a in enumerate(an):
plt.annotate(a, (x[i],y[i]))
Thanks in advance, and sorry if something isn't clear

how to change each histograph item color in python?

Korean in pictures is not important. Sorry for showing non-english character
environment : Jupyter notebook
For this dataFrame(which read csv files), I want to make bar graph which has specific colors on each item.
so, I make some code like that...
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
font_name =font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)
from matplotlib import colors as mcolors
colors=dict(mcolors.BASE_COLORS,**mcolors.CSS4_COLORS)
data = pd.read_csv('subway.csv')
subwayPassengerPerLine.plot.bar(color=['tab:blue','tab:green','tab:orange','tab:cyan','tab:purple','tab:brown','tab:green','tab:pink','tab:gold','tab:black','tab:black','tab:black','tab:black','tab:black','tab:black','tab:black','tab:black','tab:black','tab:black','tab:black','tab:black','tab:black','tab:black','tab:black','tab:black'])
I want to make like this one
But My code(upper code) doesn't change color.
how to change color in bar graph like second image? thanks
I believe, you don't need to use tab:"black" ...etc.
Just using
subwayPassengerPerLine.plot.bar(y = 'sum',color=['blue','green','orange','cyan','purple','brown','green','pink','gold','black','black','black','black','black','black','black','black','black','black','black','black','black','black','black','black'])
This can also help if you want to automate your plot color.
How to pick a new color for each plotted line within a figure in matplotlib?
Doc reference
https://python-graph-gallery.com/3-control-color-of-barplots/
Edited:
Missed the y = 'sum' field.
If you want to remove the useless legend, add this line too:
subwayPassengerPerLine.get_legend().remove()

How to save a nltk FreqDist plot?

I've tried different methods to save my plot but every thing I've tried has turned up with a blank image and I'm not currently out of ideas. Any help with other suggestions that could fix this? The code sample is below.
word_frequency = nltk.FreqDist(merged_lemmatizedTokens) #obtains frequency distribution for each token
print("\nMost frequent top-10 words: ", word_frequency.most_common(10))
word_frequency.plot(10, title='Top 10 Most Common Words in Corpus')
plt.savefig('img_top10_common.png')
I was able to save the NLTK FreqDist plot, when I first initialized a figure object, then called the plot function and finally saved the figure object.
import matplotlib.pyplot as plt
from nltk.probability import FreqDist
fig = plt.figure(figsize = (10,4))
plt.gcf().subplots_adjust(bottom=0.15) # to avoid x-ticks cut-off
fdist = FreqDist(merged_lemmatizedTokens)
fdist.plot(10, cumulative=False)
plt.show()
fig.savefig('freqDist.png', bbox_inches = "tight")
I think you can try the following:
plt.ion()
word_frequency.plot(10, title='Top 10 Most Common Words in Corpus')
plt.savefig('img_top10_common.png')
plt.ioff()
plt.show()
This is because inside nltk's plot function, plt.show() is called and once the figure is closed, plt.savefig() has no active figure to save anymore.
The workaround is to turn interactive mode on, such that the plt.show() from inside the nltk function does not block. Then savefig is called with a current figure available and saves the correct plot. To then show the figure, interactive mode needs to be turned off again and plt.show() be called externally - this time in a blocking mode.
Ideally, nltk would rewrite their plotting function to either allow to set the blocking status, or to not show the plot and return the created figure, or to take a Axes as input to which to plot. Feel free to reach out to them with this request.

How do I adjust figtext line spacing for when I have special characters in the text?

I'm trying to add an subscript to some text for my figure caption. When I do this, the line with the subscript (line 2) moves up into the line above it (line 1). Is there easy any way around this issue? Using plt.text(...) seems like it could be tedious and time consuming.
If I don't use any special characters (i.e. $_{Sun}$) with figtext it works perfectly for me.
I also had something similar happen when I was doing the same thing with legend labels, so I'm guessing that any solution to this problem will solve that as well.
Below is the relevant code which I used:
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
plt.figure(1)
figtext(0.02,0.02,"Standard composition model, Spherical geometry\nT = 5000 K, log(g) = 3.0, Microturbulance = 2, Mass = 2M$_{Sun}$\nThe x-axis covers the range of the K-bandpass\n")
plt.show()
Thank you in advanced!
This should have be a comment, if picture can be embedded in a comment. Anyway, this appears to be a bug in the interactive backend (in the following case, it is the MacOSX backend), when you save the plot into a .png or .pdf, etc, it will be rendered correctly.
Interactive:
Save it as .png or use plt.savefig():

Categories