Vivaldo Mendes
  • Research
  • Teaching
  • Lecture Notes
  • Code
  • Miscellaneous

On this page

  • Useful code-shortcuts.
  • Code for Seminar: session 1.

Code shortcuts


Useful code-shortcuts.


  1. Reading (downloading). a CSV data set
mydata = CSV.read("EZ_Inflation.csv", DataFrame)


  1. Creating a date type (object) to use in the plotting of time series if your data does not have a date type. In most cases, data sets have a date-type and this is not needed.
period1 = MonthlyDate(1997,1) : Month(1) : MonthlyDate(2021,6)


  1. Creating a slice of the data set by using the name of a column
myslice = mydata.Portugal[1:10]


  1. Creating a slice of the data set by using the rows and columns
yourslice = mydata[1:2 , 2:3]


  1. Creating a simple plot of the data for Portugal
p1 = Plot(mydata.Date, mydata.Portugal)


  1. Doing the same as in point 5, but now using rows and columns
p11 = Plot(mydata[:,2])


  1. Inserting a title into plot p1
begin
      relayout!(p1, Layout(title_text = "My first plot", title_x = 0.5))
      p1
end


  1. Plotting two time series together (Portugal and EuroZone)
begin
      p2 = Plot(Date.(period1), [mydata.Portugal  mydata.EuroZone])
      relayout!(p2, Layout(title_text = "My first plot", title_x = 0.5))
      restyle!(p2, 1:2, name = ["Portugal" , "EZ"], line_color=["blue" , "gray"], mode = "markers+lines",
  marker_size = [5 , 5], line_width = [0.5, 0.5])
      p2
end


  1. Plotting a cross plot of two time series with some useful add-ons
begin
      p3 = Plot(mydata.Portugal, mydata.EuroZone, mode = "markers", marker_color ="red")
      relayout!(p3, Layout(
            xaxis_title="Portugal", yaxis_title="EZ",
            #height = 600, width = 600
            #xaxis_range = [-1, 5.5] , yaxis_range = [-1, 5.5]
      ))
      p3
end


  1. Calculating the correlation coefficient
cor(mydata.Portugal, mydata.EuroZone)


  1. Plotting the autocorrelation function of Portuguese data
Plot(autocor(mydata.Portugal), mode = "markers+lines", line_width =0.5, marker_size = 6)


  1. Plotting the cross-correlation function between two time-series
Plot(crosscor(mydata.Portugal, mydata.EuroZone, -50:50),
mode = "lines+markers", line_width = 0.5, marker_size = 6)


  1. Creating two white noise signals with 500 observations each
begin
      noise = randn(500)
      shrek = randn(500)
end


  1. Plotting one of the two white-noise signals
begin
      fig1 = Plot(noise,
            mode = "markers+lines", marker_size = "6", line_color = "BlueViolet",
    marker_color = "Blue", line_width = 0.5,
            Layout(title_text = "White noise", title_x = 0.5, hovermode = "x"))
end


  1. Plotting the autocorrelation function of one noisy time series
begin
      Plot(autocor(noise),
            mode = "markers+lines", marker_size = "7", line_color = "BlueViolet",
    marker_color = "Blue", line_width = 0.6,
      Layout(title_text = "Autocorrelation function: white noise", title_x=0.5,
      xaxis_title = "lag", yaxis_title = "Autocorrelation"))
end


  1. Plotting a cross plot of the two noisy time-series
Plot(noise, shrek,
      mode = "markers", marker_symbol="circle", marker_size="6", marker_color= "Purple",
      Layout(width=600, height=600,
      title_text = "noise vs Shrek", title_x=0.5,
      xaxis_title = "noise",
      yaxis_title = "Shrek",
      ))


  1. Plotting the cross-correlation function between the two noisy observations
Plot(-100:100, crosscor(noise, shrek, -100:100),
                  mode="markers+lines",
                  marker_symbol="circle", marker_size="6", line_width= 0.3,
            marker_color = "Blue",
                  Layout(title_text = "Cross-correlation between noise and shrek", title_x=0.5,))


  1. Plotting the AR(1) process simulated step-by-step
Plot(y' , mode = "lines+markers", marker_symbol = "circle",
marker_size = "8", marker_color = "Blue", line_width = 0.5,
      Layout(
      title_text = "The evolution of an AR(1) process", title_x=0.5,
      xaxis_title = "time",
      yaxis_title = "y(t)",
      ))


  1. Simulate an AR(1) process with noise
begin
      ynoise = [y1  zeros(l, n-1)]                                      # Allocating space for ynoise
      
      for t = 1 : n-1                                                         # the "for" loop
            ynoise[t+1] = a + ρ * ynoise[t] + wn1[t+1]
      end
end


  1. Plotting a dynamic system of dimension 2 simulated in the classroom
begin 
      fig10 = Plot(Y',
            mode = "markers+lines", marker_size="6",line_width= 0.3,
            Layout(hovermode = "x", title_text = "A 2D System", title_x=0.5,
            xaxis_title = "time",
            yaxis_title = "y1(t) , y2(t)"))
      restyle!(fig10, 1:2, name=["y1(t)" , "y2(t)"],
  line_color = ["Blue", "red"], marker_symbol= ["circle", "circle"])
      fig10
end


Code for Seminar: session 1.


  • Download folder from here \(~~~~\) —> \(~~~~\) aqui

  • Download a CSV file here \(~~~~\) —> \(~~~~\) aqui

  • A nice article about plotting with Plotly\(~~\)here


  • Plotting a figure with button and slider simulated in the classroom: copy the code below
let

function frame_args(;duration=400, redraw=false) 
    #function to set frame attributes
    #redraw must be set on true for any other trace type different from scatter
    attr(
         frame_duration= duration,
         mode= "immediate",
         fromcurrent=true,
         redraw=redraw, 
         transition=attr(duration= duration, easing="linear")
        )
    end 

df = dataset(DataFrame, "gapminder")
df_1952 = df[df.year .== 1952, :]
fig =Plot(
    df_1952,
    x=:gdpPercap, y=:lifeExp, color=:continent , mode="markers", hovertext=:country,
    hovertemplate ="%{hovertext}year: 1952"*
    "gdpPercap: %{x}lifeExp: %{y}pop: %{marker.size}",
    marker=attr(size=:pop, sizeref=435928, sizemode="area"),
    Layout(
        title_text ="Life Expectancy vs Per Capita GDP (1952)", title_x = 0.5,
        xaxis=attr(
            type="log", range=[2, 5],
            title_text="GDP per capita (2000 dollars)"),
        yaxis=attr(title_text="Life Expectancy (years)", range=[25, 90]),
          ));
continents=["Africa", "Americas", "Asia", "Europe", "Oceania"]
years = collect(1952:5:2007)
n_frames= length(years)
frames  = Vector{PlotlyFrame}(undef, n_frames)

for k in 1:length(years)
    dfr= df[df.year .== years[k], :]
    figaux=Plot(
            dfr,
            x=:gdpPercap, y=:lifeExp, color=:continent , mode="markers", hovertext=:country,
            marker=attr(size=:pop))  
    frames[k] = frame(data=[attr(x=figaux.data[j].x,
                                 y=figaux.data[j].y,
                                 hovertext=figaux.data[j].hovertext,
                                 hovertemplate ="%{hovertext}year: $(years[k])"*
                                 "gdpPercap: %{x}lifeExp: %{y}"*
                                 "pop: %{marker.size}",
                                 marker_size=figaux.data[j].marker_size, 
                                 marker_color=figaux.data[j].marker_color,
                                 ) for j in 1:length(continents)],
                      layout=attr(title_text ="Life Expectancy vs Per Capita GDP ($(years[k]))"), #update title
                      name="fr$k", #frame name; it is passed to slider 
                      traces=[0, 1, 2, 3, 4] # the above 5-vector, data, is updating the traces fig.data[1], ....fig.data[5] 
                        ) 
end    
fig.frames=frames 
relayout!(fig, 
    height = 600,
          sliders =[attr(active=0, 
                         len= 0.9,
                         pad= attr(b= 10, t= 60),
                         x= 0.1, y=0, #slider starting position
                         xanchor= "left",
                         yanchor= "top",
                         steps=[attr(label="$(years[k])",
                                     method="animate",
                                     args=[["fr$k"], # match the frame[:name]
                                           frame_args(;)
                                 ]) for k in 1:n_frames ]
             )],
           updatemenus=[
            attr(type= "buttons",
                 buttons= [
                    attr(
                        args= [nothing, frame_args(;)],
                        label= "▶",
                        method= "animate",
                    ),
                    attr(
                        args= [[nothing], frame_args(;duration=0)],
                        label= "◼",
                        method= "animate",
                    )
                ],
                pad = attr(r=10, t=70),
                direction= "left",
                x=0.1, y=0, #button position 
                xanchor= "right",
                yanchor= "top"
            )
        ])
fig
end

  • Plotting a Plotting a dynamic heatmap simulated in the classroom: copy the code below

pdef1 = sort!(pdef, rev=false)


pdef2=select(pdef1, Not(:Ireland))


countries = names(pdef2, Not(:Years))


data_matrix=Matrix(select(pdef2, Not(:Years)))


years = pdef2.Years


begin
    data = AbstractTrace[]

    for col in names(pdef2)[2:end]
        push!(data, scatter(x=pdef2.Years, y=pdef2[!,col], mode="lines", name=col))
    end    

    layout2 = Layout(title_text="Primary deficit as a % of GDP in the EU (1995-2021)", title_x=0.05, height=660, yaxis_range = [-12.5, 10])
    Plot(data, layout2)
end

begin
    trace1 = heatmap(z=data_matrix', x=years, y=countries, colorscale="")
    layout1 = Layout(title="Primary deficit as % of GDP", xaxis_nticks=25, height = 700)
#Blues, Jet, Rainbow, Viridis
    Plot(trace1, layout1)
end
 

© 2022 Vivaldo Mendes | Made with the precious help of Ricardo Gouveia-Mendes, powered by Quarto