Search code examples
stata

Plot graph from within Mata


Consider the following toy matrix in mata:

mata: A

            1       2
     +-----------------+
   1 |   6555     140  |
   2 |   7205     135  |
   3 |   6255     140  |
   4 |   7272     138  |
   5 |  10283     133  |
   6 |   8244     136  |
   7 |   6909     144  |
   8 |   7645     138  |
   9 |  12828     134  |
  10 |   6538     137  |
     +-----------------+

If I want to draw a scatter plot using this matrix, I first need to transfer it to Stata and then also convert it to variables with the svmat command:

mata: st_matrix("A", A)

svmat A
list, separator(0)

     +-------------+
     |    A1    A2 |
     |-------------|
  1. |  6555   140 |
  2. |  7205   135 |
  3. |  6255   140 |
  4. |  7272   138 |
  5. | 10283   133 |
  6. |  8244   136 |
  7. |  6909   144 |
  8. |  7645   138 |
  9. | 12828   134 |
 10. |  6538   137 |
     +-------------+

twoway scatter A1 A2

Is there a way to directly draw the graph without leaving mata?


Solution

  • One can plot a mata matrix without first converting it to Stata variables as follows:

    twoway scatter matamatrix(A)
    

    See help twoway_mata for more details.


    Edit by @PearlySpencer:

    This can be run directly from within mata using the stata() function:

    mata: stata("twoway scatter matamatrix(A)")