Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating three-state Markov chain plot

I have following dataframe with there states: angry, calm, and tired. The dataframe below provides individual cases of transition of one state into another.

pre<-cbind(c(rep("tired",100),rep("angry",100),rep("calm",100)))
post<-cbind(c(rep("tired",50),rep("angry",70),rep("calm",100),rep("tired",80)))
df<-cbind(pre,post)
df<-as.data.frame(df)
colnames(df)<-c("pre","post")

What I would like to achieve is buidling a Markov's chain plot for three states that is also called "playground" and looks like this:

enter image description here

How would I do it in R?

Thanks in advance!

like image 332
Oposum Avatar asked Oct 25 '25 22:10

Oposum


1 Answers

We can use the markovchain package, using the plot method in diagram.

Let's first compute the transition probability matrix from your df

states<-c("tired","angry","calm")

probsCase<-function(i,j){
  sum(as.character(df$pre)==states[i] & as.character(df$post)==states[j])/sum(as.character(df$pre)==states[i])
}

transitionMatrix<-outer(1:3,1:3,Vectorize(probsCase))
colnames(transitionMatrix)<-states
rownames(transitionMatrix)<-states

Now use markovchain to initialize and plot the matrix

library(markovchain)
markovChain <- new("markovchain", states=states, transitionMatrix=transitionMatrix)
plot(markovChain,package="diagram")

EDIT:

If you have troubles installing the markovchain package, we can actually not use it and use directly the diagram package, which needs just transitionMatrix

library(diagram)
plotmat(transitionMatrix,relsize=0.7)

You can then tweak the appearance according to your taste using the options in plotmat

like image 91
adaien Avatar answered Oct 29 '25 12:10

adaien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!