课程: R for Data Science: Lunch Break Lessons

barplot

- [Instructor] Bar graphs are a really convenient way to convey information, and R has a built in bar plot graphic function. So let's take a look at how that works. The first thing I need to do is create a variable with five values in it, just for a demonstration. So I'll create five values, and into five values, I'm gonna place five numbers. I'm gonna use the fivenum function, and I'm going to feed it ChickWeight$weight, and what this does is produce five values, the minimum value, the first quartile, the median, the third quartile, and the maximum value. So let's put that into bar plot and see what happens. barplot(fivevalues), and when I hit Return, you'll see that I am presented with a bar plot in the right hand side of our studio, showing the five values that we've previously calculated. Now we can dress up that graph a bit, let's see how. I'll type in bar plot and then comma, let's first of all label those bars. And to do that, I'll use names.arg, and I'm going to use the five values to label each bar. I would also like to make this a horizontal graph, so I'm gonna use H-O-R-I-Z = TRUE. I'd like to change the colors, and to do that I use C-O-L. And I'm going to assign five values to the colors, and what this will do is select colors by number. It's a little bit of an odd way to, and there are more sophisticated ways to choose colors, but in this case, I'll demonstrate what I'm talking about. I'd also like to create a main title for the graph, so we'll type in main = Range for Chick Weights. Now when I hit Return, what you'll see is several changes. First of all, the color has been selected by the numbers inside of five values. You can see that each bar has been labeled with the value that it represents. There is a main title, and it's horizontal. So that's bar plot, it's a very simple function inside of R, it's available as part of the base package, and is useful for demonstrating relationships within a data set.

内容