Interactive Ploting - python

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

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

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()

Detailed date in cursor pos on pyplot charts

Let's say there's a time series that I want to plot in matplotlib:
dates = pd.date_range(start='2011-01-01', end='2012-01-01')
s = pd.Series(np.random.rand(1, len(dates))[0], index=dates)
The GUI backends in matplotlib have this nice feature that they show the cursor coordinates in the window. When I plot pandas series using its plot() method like this:
fig = plt.figure()
s.plot()
fig.show()
the cursor's x coords are shown in full yyyy-mm-dd at the bottom of the window as you can see on pic 1.
However when I plot the same series s with pyplot:
fig = plt.figure()
plt.plot(s.index, s.values)
fig.show()
full dates are only shown when I zoom in and in the default view I can only see Mon-yyyy (see pic 2) and I would see just the year if the series were longer.
In my project there are functions for drawing complex, multi-series graphs from time series data using plt.plot(), so when I view the results in GUI I only see the full dates in the close-ups. I'm using ipython3 v. 4.0 and I'm mostly working with the MacOSX backend, but I tried TK, Qt and GTK backends on Linux with no difference in the behavior.
So far I've got 2 ideas on how to get the full dates displayed in GUI at any zoom level:
rewrite plt.plot() to pd.Series.plot()
use canvas event handler to get the x-coord from the cursor pos and print it somewhere
However before I attempt any of the above I need to know for sure if there is a better quicker way to get the full dates printed in the graph window. I guess there is, because pandas is using it, but I couldn't find it in pyplot docs or examples or elsewhere online and it's none of these 2 calls:
ax.xaxis_date()
fig.autofmt_xdate()
Somebody please advise.
Hooks for formatting the info are Axes.format_coord or Axes.fmt_xdata. Standard formatters are defined in matplotlib.dates (plus some additions from pandas). A basic solution could be:
import matplotlib.dates
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
dates = pd.date_range(start='2011-01-01', end='2012-01-01')
series = pd.Series(np.random.rand(len(dates)), index=dates)
plt.plot(series.index, series.values)
plt.gca().fmt_xdata = matplotlib.dates.DateFormatter('%Y-%m-%d')
plt.show()

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():

Python SAC plot w/ grid

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.

Categories