简体   繁体   English

制作条形图

[英]Making a Barplot

I need to make a barplot in R.我需要在 R 中制作一个条形图。
Basically I have a dataset of baseball players that lists what team each player is on and what position each player plays at.基本上,我有一个棒球运动员数据集,其中列出了每个球员所在的球队以及每个球员所在的位置。 For example:例如:

Player    Team    Position 
1    Diamondbacks First Base
2    Diamondbacks Third Base
3    White Sox    Left Field
4    Giants       Pitcher

The actual dataset is much bigger than this, but its the same idea.实际的数据集比这个大得多,但它的想法是一样的。 I need to make a barplot of the showing the frequencies of the different positions in the teams, and I do not know how to go about doing so.我需要制作一个条形图,显示团队中不同职位的频率,但我不知道该怎么做。 Basically, all I know is barplot() , so any help would be great.基本上,我只知道barplot() ,所以任何帮助都会很棒。

Thanks!谢谢!

Consider a grouped bar plot.考虑一个分组条形图。

Modified example from this question来自这个问题的修改示例

# if you haven't installed ggplot, if yes leave this line out
install.packages("ggplot2") # choose your favorite mirror

require(ggplot2)
data(diamonds) # your data here instead
# check the dataset
head(diamonds)
# plot it, your team variable replaces 'clarity' and field position replaces 'cut'
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge") +
opts(title="Examplary Grouped Barplot")

barplot() works well if you feed it a table.如果你给它一张桌子, barplot()效果很好。 Consider the following data:考虑以下数据:

set.seed(423)
data <- data.frame(player   = 1:100,
                   team     = sample(c("Team1", "Team2", "Team3"), 100, replace = TRUE),
                   position = sample(c("Pos1", "Pos2", "Pos3", "Pos4"), 100, replace = TRUE))

First, let's make a two-dimensional table:首先,让我们制作一个二维表:

tab <- table(data$team, data$position)

One barplot you could make of data with the disposition defined by tab would be this:您可以使用tab定义的配置制作data一个条形图是这样的:

barplot(tab, beside = TRUE, legend = TRUE)

Which gives you the following:这为您提供了以下内容:在此处输入图片说明

You can run ?barplot in order to learn how to further customize your plot.您可以运行?barplot以了解如何进一步自定义您的绘图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM