Python Array Copying - python

I'm trying to figure out how to copy an array output into a new array for multiple iterations. The scenario is to run a function in a for loop with varying inputs then overlay the results on a single plot for comparison. Currently I have it running where I get three arrays from the for loop, but this results in three independent plots.
My coding is not very solid so some guidance would be appreciated. I was reading up on the list copy function but have not been able to get it to do what I want.
for z,wn in mylist:
G1 = y_numeric(z,wn)
#np.array(output[i,:])=G1.copy()
#plt.figure()
#plt.plot(t,G1[:])
#print(G1)
#print(output)

#user158430, Here is a simple example of a working code that might help you navigate through your code:
import matplotlib.pyplot as plt
import numpy as np
#creating empty list to append all y variables
all_y = []
#creating random variables
x,y1,y2,y3=np.arange(0,50,1),np.arange(50,100,1),np.arange(100,150,1),np.arange(150,200,1)
#appending only y variables into the created empty list
all_y.extend((y1,y2,y3))
#looping to plot on one single figure
for i in (all_y):
plt.plot(x,i)
plt.figure() #this code is kept outside the for loop if desired to print all the plots in one figure, if wanted the plots to be separated then indent it to match the plt.plot (i.e., put it in the loop)
This is what you should get:

Related

Adding shapes in plotly - digital signals plotting

I am trying to plot digital signals with a non existing format in plotly, which consists in thin lines in case value = 0, and thick lines in case value = 1. For doing this, I am drawing an horizontal line and adding rectangles in case signal's value=1.
As I have to plot many signals, I am working with subplots. The problem I'm having, is that shapes are only added in first subplot. I would like to know how can I add shapes to any of subplots.
import numpy as np
from plotly.subplots import make_subplots
import plotly.graph_objects as go
#Creating digital signals in array
y=np.zeros((2,40))
x=np.arange(0,4,.1)
y[0,:]=np.sign(np.cos(x*np.pi))
y[1,:]=np.sign(np.cos(x*1.5*np.pi))
y[y==-1]=0
dig_signals = make_subplots(rows=2,cols=1,subplot_titles=["signal 1", "signal 2"]
,shared_xaxes=True,x_title="time [sec]",vertical_spacing=.2)
for k in range(2):
tiempo_flancos=[] #to save the amount of state changes
if y[k,0]==1:
tiempo_flancos.append(x[0])
for i in range(1,len(x)):
if y[k,i]!=y[k,i-1]:
tiempo_flancos.append(x[i])
if y[k,-1]==1:
tiempo_flancos.append(x[-1])
dictionaries=[] #this list is needed to create shapes in plotly
for i in range(int(len(tiempo_flancos)/2)):
dictionaries.append(dict(x0=tiempo_flancos[i*2],y0=.75,
x1=tiempo_flancos[1+i*2],y1=-.75,
line_width=0,fillcolor="steelblue"))
dig_signals.add_trace(go.Scatter(x=x,y=np.repeat(0,len(x))),row=k+1,col=1)
dig_signals.update_layout(yaxis=dict(range[-3,3]),showlegend=False,shapes=dictionaries)
dig_signals.update_traces(line_color="steelblue", line_width=2.5)
dig_signals.update_yaxes(visible=False)
dig_signals
Only a couple of changes to your code: move dictionaries outside the for loop and specify yref
dictionaries=[]
for k in range(2):
tiempo_flancos=[] #to save the amount of state changes
if y[k,0]==1:
tiempo_flancos.append(x[0])
for i in range(1,len(x)):
if y[k,i]!=y[k,i-1]:
tiempo_flancos.append(x[i])
if y[k,-1]==1:
tiempo_flancos.append(x[-1])
for i in range(int(len(tiempo_flancos)/2)):
dictionaries.append(dict(x0=tiempo_flancos[i*2],y0=.75,
x1=tiempo_flancos[1+i*2],y1=-.75,
line_width=0,fillcolor="steelblue",
yref='y'+str(k+1)))
dig_signals.add_trace(go.Scatter(x=x,y=np.repeat(0,len(x))),row=k+1,col=1)
dig_signals.update_layout(yaxis=dict(range=[-3,3]),showlegend=False,shapes=dictionaries)
dig_signals.update_traces(line_color="steelblue", line_width=2.5)
dig_signals.update_yaxes(visible=False)

How to save two different matplotlib figures to two lists

data = pd.read_csv("Test data.csv")
test_data = np.array(data)
where the test_data is a time series dataset which dimension is 24×1024. Firstly, I use a for loop to draw all raw data and use map method to save raw figures in figs_list. the map method reference is here:
Get the list of figures in matplotlib
def raw_data_draw():
for i in range(len(test_data)):
draw_data = test_data[i]
plt.figure(figsize=(3.5,2.4),dpi=100)
plt.xlim([0,1024])
plt.ylim([0,1])
plt.plot(draw_data)
plt.title("signal %d"%i)
global figs_list
figs_list = list(map(plt.figure, plt.get_fignums()))
return figs_list
secondly, I reshape the (24×1024) to (24×32×32) and draw grey scale images.
def grey_data_draw():
for i in range(len(test_data)):
grey_data = test_data.reshape(len(test_data),32,-1)
plt.figure(figsize=(2.5,2.5),dpi=100)
plt.imshow(grey_data[i],origin='lower', cmap=plt.cm.gray)
plt.title("signal %d"%i)
global grey_figs_list
grey_figs_list = list(map(plt.figure, plt.get_fignums()))
return grey_figs_list
Lastly, I run these two functions as follow and get two lists.
raw_data_draw()
grey_data_draw()
the figs_list should contain 24 time series plot and grey_figs_list should contain 24 grey images.
I expect that figs_list and grey_figs_list contain different items, anyhow these tow lists contains same items,which seems figure were overwrited. I have searched much material but can not deal with it. Hope you can help me solve this problem, thanks in advance! :)
the result is show as follow, where two lists contains same items.

Why does my code add an extra frame in front of my animation?

I've been coding a Python program that will take a list from a different program, take specific values from that list, and add them to a 2D list. This subsequently creates an animation, with one frame per sub-list within the 2D list. However, when it's animated (using Celluloid), an extra frame is added in front of it that displays a graph of every sub-list at once, which disrupts the animation.
The code I'm using is this:
#Imports the relevant parts of the external modules
from matplotlib import pyplot as plt
from celluloid import Camera
from main import projectileInfo, tickRate
displacements = [] #A 2D list of all displacements
for i in projectileInfo:
displacements.append([i[1], i[0]])
print(displacements)
fig = plt.figure()
camera = Camera(fig)
for j in displacements:
x = [j[0]]
y = [j[1]]
plt.plot(x,y, color = '000000', marker = '.') #Plots the data as black points
camera.snap()
ani = camera.animate(interval = 1000*tickRate, repeat = False)
plt.show()
The issue doesn't come up if I specify values for the animation within the code itself (e.g. displacements = [[1,1], [2,2], [3,3]], but it does if projectileInfo is specified within the program.
For reference, examples for projectileInfo and tickRate are provided:
projectileInfo = [[0, 0, 2.944881550342992, 0.5724269861296344, -1.0092420948384448, -0.03813290516155552, -12.052760210752101, -0.08473978924790115], [0.2944881550342992, 0.05724269861296344, 1.739605529267782, 0.5639530072048443, -0.35217721337929575, -0.03701225346578069, -10.592616029731769, -0.0822494521461793], [0.4684487079610774, 0.11363799933344787, 0.6803439262946049, 0.5557280619902264, -0.05386624698009846, -0.03594051938005718, -9.929702771066887, -0.0798678208445715], [0.5364831005905379, 0.1692108055324705, -0.3126263508120839, 0.5477412799057693, 0.011373937998969578, -0.0349148868178283, -9.784724582224511,
-0.07758863737295177], [0.5052204655093295, 0.22398493352304744, -1.291098809034535, 0.5399824161684741, 0.19398969267459468, -0.03393274001211678, -9.378911794056458, -0.07540608891581507], [0.376110584605876, 0.27798317513989484, -2.2289899884401807, 0.5324418072768926, 0.5781971273919331, -0.03299164661811001, -8.525117494684594, -0.07331477026246667], [0.1532115857618579, 0.3312273558675841, -3.0815017379086402, 0.5251103302506459, 1.1050566133054158, -0.0320893424586703, -7.354318637099077, -0.07130964990815623], [-0.15493858802900617, 0.3837383888926487, -3.816933601618548, 0.5179793652598302, 1.6954652941177968, -0.031223717732420407, -6.042299346404897, -0.06938603940537869], [-0.536631948190861, 0.43553632541863174, -4.421163536259038, 0.5110407613192923, 2.2747457012945764, -0.030392804526055698, -4.75500955267872, -0.0675395656134571], [-0.9787483018167649, 0.486640401550561, -4.89666449152691, 0.5042868047579466, 2.7903609807178054, -0.029594765491590475, -3.6091978206270996, -0.06576614553686772], [-1.4684147509694558, 0.5370690820263556, -5.25758427358962, 0.4977101902042599,
3.216860139839751, -0.02882788356578406, -2.6614219114672206, -0.06406196347952013], [-1.9941731783284178, 0.5868401010467816, -5.523726464736342, 0.49130399385630785, 3.5507821034099836, -0.028090552623374627, -1.9193731035333705, -0.062423450274165834], [-2.546545824802052, 0.6359705004324124, -5.715663775089679, 0.48506164882889125, 3.801833041871401, -0.027381268968280633, -1.3614821291746655, -0.06084726437395696], [-3.11811220231102, 0.6844766653153016, -5.851811988007145, 0.47897692239149553, 3.985110999814779, -0.026698623577869795, -0.9541977781893805, -0.05933027461748843]]
tickRate = 0.05
I haven't managed to reproduce the problem in any test program, not even within the same virtual environment as the original code.

Declare a function to do exponential smothing on data

I am trying to do an exponential smothing in Python on some detrended data on a Jupyter notebook. I try to import
from statsmodels.tsa.api import ExponentialSmoothing
but the following error comes up
ImportError: cannot import name 'SimpleExpSmoothing'
I don't know how to solve that problem from a Jupyter notebook, so I am trying to declare a function that does the exponential smoothing.
Let's say the function's name is expsmoth(list,a) and takes a list list and a number a and gives another list called explist whose elements are given by the following recurrence relation:
explist[0] == list[0]
explist[i] == a*list[i] + (1-a)*explist[i-1]
I am still leargnin python. How to declare a function that takes a list and a number as arguments and gives back a list whose elements are given by the above recurrence relation?
A simple solution to your problem would be
def explist(data, a):
smooth_data = data.copy() # make a copy to avoid changing the original list
for i in range(1, len(data)):
smooth_data[i] = a*data[i] + (1-a)*smooth_data[i-1]
return smooth_data
The function should work with both native python lists or numpy arrays.
import matplotlib.pyplot as plt
import numpy as np
data = np.random.random(100) # some random data
smooth_data = explist(data, 0.2)
plt.plot(data, label='orginal')
plt.plot(smooth_data, label='smoothed')
plt.legend()
plt.show()

Necessary data structure for making heatmaps in Python

EDIT Just realized the way I was parsing in the data was deleting numbers so I didn't have an array for the correct shape. Thanks mgilson, you provided fantastic answers!
I'm trying to make a heatmap of data using python. I have found this basic code that works:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(3,3)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)
plt.show()
f.close()
However, when I try to put in my data, which is currently formatted as a list of lists (data=[[1,2,3],[1,2,3],[1,2,3]]), it gives me the error: AttributeError: 'list' object has no attribute 'shape.'
What is the data structure that np.random.rand() produces/ python uses for heatmaps? How do I convert my list of lists into that data structure? Thanks so much!
This is what my data looks like, if that helps:
[[0.174365079365079, 0.147356200527704, 0.172903394255875, 0.149252948885976, 0.132479381443299, 0.279736780258519, 0.134908163265306, 0.127802340702211, 0.131209302325581, 0.100632627646326, 0.127636363636364, 0.146028409090909],
[0.161473684210526, 0.163691529709229, 0.166841698841699, 0.144, 0.13104, 0.146225563909774, 0.131002409638554, 0.125977358490566, 0.107940372670807, 0.100862068965517, 0.13436641221374, 0.130921518987342],
[0.15640362225097, 0.152472361809045, 0.101713567839196, 0.123847328244275, 0.101428924598269, 0.102045112781955, 0.0999014778325123, 0.11909887359199, 0.186751958224543, 0.216221343873518, 0.353571428571429],
[0.155185378590078, 0.151626168224299, 0.112484210526316, 0.126333764553687, 0.108763358778626],
[0.792675, 0.681526248399488, 0.929269035532995, 0.741649167733675, 0.436010126582278, 0.462519447929736, 0.416332480818414, 0.135318181818182, 0.453331639135959, 0.121893919793014, 0.457028132992327, 0.462558139534884],
[0.779800766283525, 1.02741401273885, 0.893561712846348, 0.710062015503876, 0.425114754098361, 0.388704980842912, 0.415049608355091, 0.228122605363985, 0.128575796178344, 0.113307392996109, 0.404273195876289, 0.414923673997413],
[0.802428754813864, 0.601316326530612, 0.156620689655172, 0.459367588932806, 0.189442875481386, 0.118344827586207, 0.127080939947781, 0.2588, 0.490834196891192, 0.805660574412533, 3.17598959687906],
[0.873314136125655, 0.75143661971831, 0.255721518987342, 0.472793854033291, 0.296584980237154]]
It's a numpy.ndarray. You can construct it easily from your data:
import numpy as np
data = np.array([[1,2,3],[1,2,3],[1,2,3]])
(np.asarray would also work -- If given an array, it just returns it, otherwise it constructs a new one compared to np.array which always constructs a new array)

Categories

Resources