Abhijith Chandran
Abhijith Chandran

Reputation: 41

Plotting in C# using mathematica

Please help me in plotting data that is send from C# to mathematica kernel. I want to write mathematica code from C# and plot spectroscopic data. I have added the necessary assembly and references, I think. My C# code is below.

public void button2_Click(object sender, System.EventArgs e)
{
       double baseline;
       int indexOfPeak;
       int minimumIndicesBetweenPeaks;
       int numberOfPixels; 
       double[] spectrum;
       int startingIndex;
       if (spectrometerIndex == -1)
          return; 
       numberOfPixels = wrapper.getNumberOfPixels(spectrometerIndex);
       wrapper.setIntegrationTime(spectrometerIndex, 500000);
       wrapper.setBoxcarWidth(spectrometerIndex, 10);
       wrapper.setCorrectForElectricalDark(spectrometerIndex, 1);
       spectrum = (double[])wrapper.getSpectrum(spectrometerIndex);
       for (int index = 0; index < numberOfPixels; ++index)
       {
           listBox2.Items.Add("pixel[" + index + "] = " +
           spectrum[index]);               
       }
       MathKernel mathKernel = new MathKernel();
       mathkernel.ListPlot[spectrum];
    }            
}

Upvotes: 2

Views: 362

Answers (1)

Chris Degnen
Chris Degnen

Reputation: 8655

Here are a couple of methods, based on a post here

You may need to format your spectrum data suitably for Mathematica, e.g.

string data = "1.234, 2.345, 3.456";

For GIF format

MathKernel mathKernel = new MathKernel();
mathKernel.CaptureGraphics = true;
mathKernel.GraphicsFormat = "GIF";
mathKernel.Compute("Show[ListPlot[{" + data + "}]]");
mathKernel.Graphics[0].Save("C:\\Temp\\plot.gif", System.Drawing.Imaging.ImageFormat.Gif);

For enhanced metafile (scalable graphics)

MathKernel mathKernel  = new MathKernel();
mathKernel.Compute("ExportString[ListPlot[{" + data + "}], {\"Base64\", \"EMF\"}]");
byte[] decodedBytes = Convert.FromBase64String(mathKernel.Result.ToString());
File.WriteAllBytes("C:\\Temp\\plot.emf", decodedBytes);

Upvotes: 2

Related Questions