I have always been frustrated that python does not have a nice GUI builder similar to what XCode provides.  Since I am a scientist and engineer, I am really fond of the combination matplotlib/scipy/numpy.  Here I will give an example of how to combine the two using the python cocoa bridge that is build into the python that comes with the operating system (in my case Mountain Lion OS X 10.8).  The only thing that you need to install for this example to work is the SciPySuperpack.

Here is the link to my example: github.com/hstrey/ShowMatPlotLib

Here is how it’s done. The basic idea is that the python code creates a png file of the graph and that this graph is sent to the Cocoa program via a NSData object. I then convert NSData into a png image and display it. To show how fast this happens, I added a slider to change the frequency of the sine function that is being displayed. Every time you change the setting a new graph is created and displayed. This technique is not suitable for graphs that need to change dynamically at a high frame rate but for most applications it should work.

First the Cocoa part:




untitled

//
//  SMPLAppDelegate.m
//  ShowMatPlotLib
//
//  Created by Helmut Strey on 4/23/12.
//  Copyright (c) 2012 Stony Brook University. All rights reserved.
//
 
#import "SMPLAppDelegate.h"
#include "Python/Python.h"
 
// Global pointer to app delegate
SMPLAppDelegate* myprogram;
 
// sendGraph function for sending graph through NSData
PyObject* sendGraph(PyObject* self, PyObject* pArgs)
{
    char* GraphStr = NULL;
    int length;
    if (!PyArg_ParseTuple(pArgs, "s#", &GraphStr,&length)) return NULL;
     
    NSLog(@"%i",length);
    [myprogram pythonOut: [NSData dataWithBytes: GraphStr length:length]];
     
    Py_INCREF(Py_None);
    return Py_None;
}
 
static PyMethodDef sendGraphMethods[] = {
    {"SendGraph", sendGraph, METH_VARARGS, "submit string"},
    {NULL, NULL, 0, NULL}
};
 
 
@implementation SMPLAppDelegate
 
@synthesize window = _window;
@synthesize matplotlibView = _matplotlibView;
@synthesize freq=_freq;
 
- (void)setFreq:(double)freq
{
    _freq=freq;
    NSString *mystring = [[NSString alloc] initWithFormat:@"drawplot(%f)\n" , freq];
    PyRun_SimpleString([mystring UTF8String]);
}
 
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    myprogram=self;
    Py_Initialize();
     
    Py_InitModule("MPL", sendGraphMethods);
    NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"init" ofType:@"py"];
     
    // load the main script into the python runtime
    FILE *mainFile = fopen([scriptPath UTF8String], "r");
    PyRun_SimpleFile(mainFile, (char *)[[scriptPath lastPathComponent] UTF8String]);
     
    self.freq=50;
     
}
 
- (void)pythonOut: (NSData*)pngimage
{
    NSImage *matplotlibGraph = [[NSImage alloc] initWithData:pngimage];
    [self.matplotlibView setImage:matplotlibGraph];
    [self.matplotlibView setNeedsDisplay:YES];
}
 
@end


And here is the python part (MPL is a module that I inserted from the Cocoa side):




untitled

import MPL
import numpy as np
import StringIO
from pylab import *
 
time=linspace(0,6.3,500)
 
def drawplot(freq):
    f=StringIO.StringIO()
    figure(num=None, figsize=(9,7),dpi=60)
    a=np.sin(freq*time)
    plot(time,a)
    savefig(f,format='png')
    out=f.getvalue()
    f.close()
    MPL.SendGraph(out)


18 thoughts on “MatPlotLib running in Cocoa under Xcode

  1. Hi.

    I’m quite interested in this. I’ve made some microscopic examples of simple GUIs using PyObjC and XCode as proof of concept. I haven’t been able to get you sample project to build (perhaps due to my 10.7 environment?). Could you possible provide a bit more of a tutorial?

    Thanks much.

    Jerry LeC.

  2. Cactus Jack Hoodie – a must-have for every streetwear enthusiast. Designed in collaboration with the iconic Travis Scott, this hoodie blends high fashion with urban edge.

  3. Sp5der Hoodies
    are perfect for daily life, outdoor activities, fitness enthusiasts, and gaming sessions. They’re great for running errands, hiking, camping, working out, or just lounging around.

  4. Looking for the perfect streetwear hoodie? The Corteiz 4Starz Alcatraz Black Hoodie is just what you need. Discover it at Corteiz!

  5. Corteiz

    Looking for the perfect streetwear hoodie? The Corteiz 4Starz Alcatraz Black Hoodie is just what you need. Discover it at Corteiz!

  6. Mounjaro Mexico for Weight Loss Without Prescription. We offer Mounjaro at an affordable price worldwide. Purchasing Mounjaro in Mexico through our online pharmacy can save you up to 90%. Place your order now for prompt delivery.
    Mounjaro Mexico

  7. Hellstar Clothing is a distinctive fashion brand known for its edgy and rebellious aesthetic. It combines elements of streetwear and high fashion to create unique, bold designs that resonate with a young, trendsetting audience.

  8. Step into the world of fashion excitement with Hellstar’s amazing clothes. We have everything you need to look and feel your best, whether you are attending a special event or dressing for the everyday. Explore our incredible collection today.

  9. Cactus Jack hoodies are celebrated for their bold and unique designs. Featuring vibrant graphics, intricate embroidery, and a mix of striking colors, these hoodies stand out in a crowded market.

  10. What genuinely unites Paul Smith T-shirts aside is their commitment to considerate layout details. Here are some signature factors to look for: A playful and recognizable emblem, the Zebra emblem adds a touch of Paul Smith’s signature quirkiness to many of their T-shirts. It’s frequently reimagined in unique colors and styles, including a touch of diffused yet excellent detail. Some Paul Smith T-shirts feature contrasting hues on the collar and cuffs. This provides a touch of visual interest and elevates the primary T-blouse silhouette. Paul Smith prioritizes first-rate fabric.
    paul-smith-t-shirt/

  11. Top off your look with the Stussy clothing Classic Trucker Hat. Featuring a mesh back for breathability and a bold logo on the front, this hat is a versatile accessory for any casual outfit.

  12. Add a pop of color to your wardrobe with the Stussy clothing Dyed Hoodie. This piece is uniquely dyed for a one-of-a-kind look, complete with a kangaroo pocket and adjustable hood for added comfort.

    stussy clothing

  13. Essentials! Clothing, launched in 2018 by Jerry Lorenzo under the Fear of God label, is renowned for its minimalist designs and high-quality streetwear essentials. The brand focuses on comfort and everyday wear, offering accessible yet stylish pieces like the iconic Essentials hoodie.

  14. Discover the epitome of Clothing elegance with Corteiz Official! Our exclusive collection seamlessly merges trendsetting design with unparalleled comfort, promising a stride above the rest

  15. Stay updated with the latest T20 cricket news, match schedules, player stats, and live scores. Explore in-depth analysis, expert opinions, and highlights from your favorite T20 cricket leagues worldwide.https://t20cricketzone.com/

Comments are closed.