Is there a method to connect a point with previous a point? - python

I am trying to use plt.scatter to generate multiple points and I want to connect each point with the previous one. For my x-axes I need to use the format time.time() or something that will allow me to draw points each second.
I tried to use plt.plot(), but that will result in changes I don't need.
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import time
ts = time.time()
kraft = 2300
for i in range(10):
ts1 = ts + i
kraft1 = kraft + i
plt.scatter(ts1, kraft1)
plt.show()
I expect to have multiple points connected to the former point.
Thanks for you answers.

The straightforward solution is to use save your values in a list and plot all of them at once using style '-o' which represents a line and a marker. You don't need extra variables ts1 and kraft1 here
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import time
ts = time.time()
kraft = 2300
x, y = [], []
for i in range(10):
x.append(ts + i)
y.append(kraft + i)
plt.plot(x, y, '-o')

Related

Find all the turning points from a temperature dataset

I'm trying to get the turning points (peaks and valleys) of this data.
Here is what I'm trying,
import scipy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from peakdetect import peakdetect
df = pd.read_csv('temp_sample.csv')
x = df['time'].to_list()
y = df['temp'].to_list()
turnpoints = peakdetect(y, x, lookahead=20)
print(turnpoints)
peaks = np.array(turnpoints[0])
valleys = np.array(turnpoints[1])
plt.plot(x,y)
plt.plot(peaks[:,0], peaks[:,1], 'ro')
plt.plot(valleys[:,0], valleys[:,1], 'ko')
This does not plot all the turnpoints. This is a temperature dataset, so we can see the rise, steady and fall states of the temperature. For steady state, this script only plots one end. Is it possible to get all the turnpoints in the graph no matter the state.

Plot specific element values in matplotlib

I have a list as below:
freq = [29342, 28360, 26029, 21418, 20771, 18372, 18239, 18070, 17261, 17102]
I want to show the values of n-th and m-th element of the x-axis and draw a vertical line
plt.plot(freq[0:1000])
For example in the graph above, the 100th elements on the x-axis - how can I show the values on the line?
I tried to knee but it shows only one elbow. I suggest it is the 50th element? But what is exactly x,y??
from kneed import KneeLocator
kn = KneeLocator(list(range(0, 1000)), freq[0:1000], curve='convex', direction='decreasing')
import matplotlib.pyplot as plt
kn.plot_knee()
#plt.axvline(x=50, color='black', linewidth=2, alpha=.7)
plt.annotate(freq[50], xy=(50, freq[50]), size=10)
You might think that everybody knows this library kneed. Well, I don't know about others but I have never seen that one before (it does not even have a tag here on SO).
But their documentation is excellent (qhull take note!). So, you could do something like this:
#fake data generation
import numpy as np
x=np.linspace(1, 10, 100)
freq=x**(-1.9)
#here happens the actual plotting
from kneed import KneeLocator
import matplotlib.pyplot as plt
kn = KneeLocator(x, freq, curve='convex', direction='decreasing')
xk = kn.knee
yk = kn.knee_y
kn.plot_knee()
plt.annotate(f'Found knee at x={xk:.2f}, y={yk:.2f}', xy=(xk*1.1, yk*1.1) )
plt.show()
Sample output:

How can i have my code print more than one graph at a time?

I am quite new to python so please bear with me.
My code is below:
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
df = pd.read_csv(r"/Users/aaronhuang/Desktop/ffp/exfileCLEAN2.csv", skiprows=[1])
magnitudes = df['Magnitude '].values
times = df['Time '].values
zscores = np.abs(stats.zscore(magnitudes, ddof=1))
outlier_indicies = np.argwhere(zscores > 3).flatten()
print(times[outlier_indicies])
window = 10
num = 1
x = times[outlier_indicies[num]-window:outlier_indicies[num]+window+1]
y = magnitudes[outlier_indicies[num]-window:outlier_indicies[num]+window+1]
plt.plot(x, y)
plt.xlabel('Time (units)')
plt.ylabel('Magnitude (units)')
plt.show()
fig = plt.figure()
fig.savefig("/Users/aaronhuang/Downloads")
Is there a way I can print all the graphs separately once?. Deleting num has not worked.
Thank you in advance.
You can put the plots inside a for loop, and repeat as many times as you like, with different variables for each step if needed. Most software will show the plots either in multiple plot windows, or output them in a long strip you can scroll through. If you use Spyder however, they will play back to back, with each plot being a frame.
Also, if you want to print multiple plots, you have to put the plt.show() inside the loop as well, putting it after the loop will show all the values on a single plot.
For example:
import matplotlib.pyplot as plt
x_values = [1,2,3,4,5,6,7]
for x in x_values:
y = x**2
plt.plot(x,y,"o")
plt.axis([0,50, 0,50])
plt.show()

Plotting large datasets with pandas

I convert an oscilloscope dataset with millions of values into a pandas DataFrame. Next step is to plot it. But Matplotlib needs on my fairly powerful machine ~50 seconds to plot the DataFrame.
import pandas as pd
import matplotlib.pyplot as plt
import readTrc
datX, datY, m = readTrc.readTrc('C220180104_ch2_UHF00000.trc')
srx, sry = pd.Series(datX), pd.Series(datY)
df = pd.concat([srx, sry], axis = 1)
df.set_index(0, inplace = True)
df.plot(grid = 1)
plt.show()
Now I found out that there is a way to make matplotlib faster with large datasets by using 'Agg'.
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import matplotlib.pyplot as plt
import readTrc
datX, datY, m = readTrc.readTrc('C220180104_ch2_UHF00000.trc')
srx, sry = pd.Series(datX), pd.Series(datY)
df = pd.concat([srx, sry], axis = 1)
df.set_index(0, inplace = True)
df.plot(grid = 1)
plt.show()
Unfortunately no plot is shown. The process of processing the plot takes ~5 seconds (a big improvement) but no plot is shown. Is this method not compatible with pandas?
You can use Ploty and Lenspy (was built to solve this exact problem). Here is an example of how you can plot 10m points on scatter plot. This plot runs super fast on my 2016 MacBook.
import numpy as np
import plotly.graph_objects as go
from lenspy import DynamicPlot
# First, let's create a very large figure
x = np.arange(1, 11, 1e-6)
y = 1e-2*np.sin(1e3*x) + np.sin(x) + 1e-3*np.sin(1e10*x)
fig = go.Figure(data=[go.Scattergl(x=x, y=y)])
fig.update_layout(title=f"{len(x):,} Data Points.")
# Use DynamicPlot.show to view the plot
plot = DynamicPlot(fig)
plot.show()
# Plot will be available in the browser at http://127.0.0.1:8050/
For your use case (again, I cannot test this since I don’t have access to your dataset):
import pandas as pd
import matplotlib.pyplot as plt
import readTrc
from lenspy import DynamicPlot
import plotly.graph_objects as go
datX, datY, m = readTrc.readTrc('C220180104_ch2_UHF00000.trc')
srx, sry = pd.Series(datX), pd.Series(datY)
fig = go.Figure(data=[go.Scattergl(x=srx, y=sry)])
fig.update_layout(title=f"{len(x):,} Data Points.")
# Use DynamicPlot.show to view the plot
plot = DynamicPlot(fig)
plot.show()
Disclaimer: I am the creator of Lenspy

matplotlib: Continuously overwriting

I would like to plot my intermediate results and want to see how is the algorithm progressing. I have posted a demo code too. Lets say my algorithm goes for 20 epochs and I want to plot the result of every epoch in a same file. I tried with following demo code. But I can not see any plot on a.png.
Could someone help me how could I do it?
import matplotlib.pylab as plt
import numpy as np
for i in range(20):
y = np.random.random()
plt.plot(i, y)
plt.savefig('a.png')
You have to provide the whole history in your variables e.g. as a list:
import matplotlib.pylab as plt
import numpy as np
# creates two lists with the same length
x = range(20)
y = [0] * 20
for i in x:
y.insert(i, np.random.random())
plt.plot(x, y)
plt.savefig('plot_%d.png' % i)

Categories