I need to make a barplot in 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.
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. 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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.