Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Creating functions

From: Interactive Data Visualization with Processing

Video: Creating functions

One of the great ways of writing your code is to use shortcuts, such as functions. Now, we've been using a lot of functions up to this point. For instance, setup and draw and mousepress are all functions. But you can also have what are called custom or user-created functions, where you create your own shortcuts, and they allow you to use modular code, and it can save a lot of time in repeating things. So the first thing that I am going to do I this sketch is just put a little comment at the top with the sketch name.

Creating functions

One of the great ways of writing your code is to use shortcuts, such as functions. Now, we've been using a lot of functions up to this point. For instance, setup and draw and mousepress are all functions. But you can also have what are called custom or user-created functions, where you create your own shortcuts, and they allow you to use modular code, and it can save a lot of time in repeating things. So the first thing that I am going to do I this sketch is just put a little comment at the top with the sketch name.

And then I'm going to create the setup function. Let's do a void setup, small amount of text in here. I am going to do a size, 600 x 200, turn on the anti-aliasing. And I am als, going to set the frame rate to be a little slow on these. I'll leave it at 2 frames per second. So that's the first part of this sketch. I am going to save that. And then what I'm going to do is I'm not trying to create two different functions. I'll show them to you, each one at a time.

The first one I'm going to do, I'm going to put these in the draw block. So I do void, draw, which we've done many times before. And what I'm going to do in here is I'm going to have a background refresh and then I'm going to make my life very easy and I'm going to draw a little pacMan shape. And I'm going to create a pacMan function where this is all the code that I need to make it run. I'm going to save this for a moment. Now I can do the code directly beneath, but one of the interesting things that you can do also is that Processing allows you to create several tabs.

You see that we already have one tab here, this Ex09_01; that's the main one. And if you want to, to emphasize the modularity and facilitate the keeping of the code, you can add a second tab to this one. So for instance, I'm going to come over here to this arrow, click on that, and create a new tab. And this new tab, it's asking me for the name. I'm going to call it PacMan. Actually, I want to give it a lowercase pacMan so that it matches.

And I see I have a second tab open, and this is where I get to define the pacMan function. And here's what I'm going to do. The first thing you need to do is you need to give the return type. Now, in this setup in the drawing and all that, it's been void, and since this pacMan function isn't returning any data, it's going to be void also. And then I give the name of the function, which I call pacMan, and I'm going to put it here in some curly quotes.

And then what I need to do is I start putting in the code to draw the pacMan. So, for instance, I don't want any outlines, so I do no stroke. And then what I want is some random variables to position the shapes. So I'm going to have a floating-point variable x, and that's just going to be a random, anywhere in the window width will do it. I also want it to be anywhere from top to bottom.

These are just going to be the center points for the shape. I can do a random height. And then I want to have different diameters for the pacMan, so I'm going to do that one as d, for diameter, and random, except that one I don't want going down to 0. I'll make it so they go from 20 to 100. So I've got three variables that are going to be generated randomly. And then I specify the fill. A nice bright yellow is going to be FFEF00.

And then finally, to draw the pacMan shape, all I need is the arc function. And for the arc, you specify this center point, and that's going to be x and y, which are going to be randomly generated right above this. And then the diameter, so the width and the height, I want to be the same, so it's circular. So that's the variable d that I defined above. And then I need to define where the shape starts and where it stops. And what I'm going to do is I'm going to start it at PI*0.2. That's just around 4 o'clock on the circle.

And then it's going to go around clockways till it gets to about 2 o'clock. So that's going to be PI*1.8, and then that is my function. So now, when I go back to my first tab, this is all the code I need. All I need to say is draw a pacMan. And then over here, I have all this code and if I want to, I can use that again later. In fact, let me show you one thing that happens in this sketch folder when you create a separate tab. I move this over to the side. I've got my sketch folder open.

There's the sketch folder and now you see that we actually have two files in there. These are PDE files. The first one is the main tab with the exercise, but the function, when I put it on a separate tab, got its own little file here. And that's one of the things that makes it really easy to copy and paste this into other sketches in the future. Anyhow, I'm going to come back and maximize this one. And I'm simply going to run it by pressing Ctrl+R. And now what I have is randomly sized pacMan figures, popping around at random places on the screen.

It's not an exciting function, but it does give you an idea of how you can create code that is modular and very simple to maintain. I'll close that by hitting Escape. All I had to do for that one was call on the pacMan function. And it's operating at 2 frames per second, and that's how it works. Now if you want to see something interesting-- I'll just turn off the background for a minute. So now, each previous pacMan will remain, and pretty soon we'll get all full. Anyhow.

And what I want to show you though, is that you can actually draw something more sophisticated than this. This is an example I chose because it was really easy, but I want you to see that you can do something that's more relevant to data visualization with this as well. What I'm going to be doing in this case is I'm going to be drawing a function to make a bar graph. So I'm just going to come over and create my bar graph function on a new page first. First, I'm going to click to create a new tab, and this one I'll call barGraph.

And now what I have, barGraph function. I can save that. And I'm going to create a function that allows people to enter some values on the original page, and then it will integrate them automatically. So I'm going to call void, because it doesn't return any calculations, and I'm just going to call it bar. The first thing I'm going to want is an indication of where it should go-- that's going to be the I--as well, as how many there are in total. int I'm going to put here for the outcome. That is going to be, really, how tall does the bar need to be? And then I'm going to have a string variable also, for the label of the bar.

So those are the parameters that are going to be going into it. They need to be provided by the users. So I put in my curly brackets. And then the first thing is we're going to calculate the values for the bars. And in this case, what I am going to do is again create a little function that calculate the x coordinates for the bars. So it's going to be x is a function of--we are going to take the width of the window times i.

We are going to divide that by n+1. This is going to help just determine where each of the bars should go. And I'll put here "calculates the x coordinate for each bar." The next line, I'm going to decide how much space to put between the bars. I'm just going to make this a constant for all of them, and that's going to be 20 pixels. Sets space between bars and pixels.

Next, I'm going to have a calculation to decide how wide each one of the bars should be, depending on how many there are, and the space between them. So I'm going to do float for any variable wide is equal to the width of the window minus the space between the bars, times and plus 1, divided by n. It's a kind of complicated-looking formula, but it's just a way of spacing things out. Then we need a little code to draw the bars.

What I'm going to do first is I'm going to create rectangles, but I want to center them; it makes it little easier to place them with these formulas. I am going to then turn off the outline. I'm going to put the fill in, a red color. And then we are going to put in rectangles. These are formulas that I use to determine where they should go and how high they should be. I'm also going to have labels on these.

I am going to center the text. I'm going to put a fill on there that's relatively light. And then we are going to replace the text by using the label that it gets from above. It goes to the same center position as the bar, and it's going to go near the top of the bar on the inside. That's what this formula does.

Then we are going to have a little black text that will be the value for what it goes on, so that's going to be called outcome, x and height - outcome. The one it before actually goes slightly above the bar. This one actually goes inside it. So that's my function. Now let's go back to here. I'm going to comment out the pacMan function for right now, and instead I'm going to ask for a few bars to be drawn. And all I have to do is say bar. And I could say this is going to be the first of 6, and the outcome value is 150, and it is for Region 1. I need to have a string variable there.

And once I get those, I'm just going to copy that, one, two. And this will be second of 6, the third, the fourth, the fifth, and the sixth. Now I'm just change the value for each one of these. I'll make that one 130, this one 122, this one 109, this one 87, and this one 42, and then I just change the region names to region 2, 3, 4, 5, 6.

And there are ways that you can have Processing actually calculate the counts and which each bar is. But for right now, I'm just going to leave it like that and when I press Run, now I have bar charts that are spaced automatically and have their labels and the values above them. This is a very simple kind of chart, but the idea here is you see how I used a function to create something that could be repeated again and again, with the small variations that I specifically requested. And functions are going to be a big part of being able to create customs,= sketches and visualizations, make your life little bit easier, and have some fascinating results.

Show transcript

This video is part of

Image for Interactive Data Visualization with Processing
Interactive Data Visualization with Processing

72 video lessons · 12214 viewers

Barton Poulson
Author

 
Expand all | Collapse all
  1. 3m 16s
    1. Welcome
      58s
    2. What you should know
      1m 22s
    3. Using the exercise files
      56s
  2. 11m 51s
    1. Overview of data visualization
      11m 51s
  3. 11m 53s
    1. Installing Processing
      3m 38s
    2. Overview of Processing
      4m 5s
    3. Exploring libraries
      4m 10s
  4. 1h 1m
    1. Basic setup
      7m 31s
    2. Drawing points
      4m 37s
    3. Drawing lines
      5m 6s
    4. Drawing ellipses and circles
      5m 24s
    5. Drawing arcs
      6m 54s
    6. Drawing rectangles and squares
      4m 58s
    7. Drawing quadrangles
      3m 25s
    8. Drawing triangles
      2m 55s
    9. Drawing polygons
      3m 37s
    10. Drawing simple curves
      4m 54s
    11. Drawing complex curves
      6m 46s
    12. Drawing Bézier curves
      5m 38s
  5. 54m 3s
    1. Introduction to variables
      10m 44s
    2. Understanding variable scope
      6m 53s
    3. Modifying variables
      9m 8s
    4. Creating arrays
      9m 53s
    5. Modifying arrays
      6m 37s
    6. Creating strings
      7m 3s
    7. Modifying strings
      3m 45s
  6. 1h 2m
    1. Incorporating randomness
      7m 59s
    2. Using Perlin noise
      4m 24s
    3. Shuffling with Java
      3m 30s
    4. Specifying line attributes
      8m 2s
    5. Changing placement modes
      5m 45s
    6. Understanding color attributes and functions
      4m 16s
    7. Exploring color spaces
      7m 44s
    8. Using color palettes
      7m 5s
    9. Transforming the grid
      8m 38s
    10. Exploring the attribute matrix
      5m 33s
  7. 52m 7s
    1. Building code blocks
      5m 57s
    2. Writing a while loop
      3m 52s
    3. Using for loops
      5m 35s
    4. Creating conditionals
      14m 50s
    5. Working with easing
      10m 51s
    6. Creating spirals
      11m 2s
  8. 18m 55s
    1. Mouse tracking
      3m 54s
    2. Hovering and clicking
      11m 16s
    3. Understanding keyboard interaction
      3m 45s
  9. 27m 32s
    1. Specifying fonts
      6m 43s
    2. Using images
      5m 51s
    3. Playing a video loop
      6m 20s
    4. Exporting video
      3m 47s
    5. Adding sound
      4m 51s
  10. 20m 49s
    1. Creating functions
      11m 48s
    2. Creating classes and objects
      9m 1s
  11. 31m 10s
    1. Using embedded data
      5m 26s
    2. Working with appended text data
      6m 4s
    3. Working with appended tabular data
      10m 26s
    4. Reading XML data
      9m 14s
  12. 48m 17s
    1. Generating dot plots
      11m 11s
    2. Building scatter plots
      10m 0s
    3. Making line plots
      9m 55s
    4. Creating bar charts
      9m 12s
    5. Checking out examples of maps, hierarchies, and networks
      7m 59s
  13. 20m 57s
    1. Introducing some principles of 2D design
      13m 44s
    2. Understanding color theory
      7m 13s
  14. 24m 46s
    1. Interacting with zooming, rotating, and sliding
      6m 26s
    2. Implementing slicing
      6m 47s
    3. Using rollovers
      5m 58s
    4. Introducing the GUI libraries
      5m 35s
  15. 10m 35s
    1. Sharing via OpenProcessing and other sites
      3m 19s
    2. Saving as a desktop application
      2m 42s
    3. Saving as JavaScript
      1m 47s
    4. Saving as an Android application
      2m 47s
  16. 2m 38s
    1. Where to go from here
      2m 38s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Interactive Data Visualization with Processing.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.