用ggplot2绘制10个最高的条,而不是70条

时间:2019-05-08 08:05:13

标签: r ggplot2

对于我的任务,我有一个奥运金牌得主的数据集,需要制作一个堆积的条形图。我目前有以下情节。

enter image description here

我的代码如下:



ggplot(data = medalwinners, aes(x = Team, fill = Medal)) +
  geom_bar() 

我的数据:

structure(list(Name = c("Juhamatti Tapio Aaltonen", "Giovanni Abagnale", "Patimat Abakarova", 
    "Luc Abalo", "Luc Abalo", "Jeremy Abbott" ), Sex = c("M", "M", "F", "M", "M", "M"), 
  Age = c(28L, 21L, 21L, 27L, 31L, 28L), 
  Height = c(184L, 198L, 165L, 182L, 182L, 175L ), 
  Weight = c(85, 90, 49, 86, 86, 70), 
  Team = c("Finland", "Italy", "Azerbaijan", "France", "France", "United States"), 
  NOC = c("FIN", "ITA", "AZE", "FRA", "FRA", "USA"), ), 
  Medal = c("Bronze", "Bronze", "Bronze", "Gold", "Bronze")), ., 
  row.names = c(NA, 6L), 
  class = "data.frame")

如何调整图表,使其显示前10个国家/地区的条形图?

谢谢!

2 个答案:

答案 0 :(得分:0)

嗨,我最近发现了一种制作子集的简单方法 ggplot的示例,“ test”只是ggplot对象 那么最后一行是有用的东西。

test.1 <- 
    ggplot(data = test, aes(x = Team, fill = Medal)) +
    geom_bar() 
test.1

# Get the name of the Teams greater than 10
n.1 <- table(test.1$data$Team) %>% .[.>1] %>% names()

# pipe subset into ggplot
test.1 %+% subset(test.1$data, Team %in% n.1 )

# or pipe a subset of a df into ggplot
test.1 %+% (test.1$data %>% group_by(Team) %>% filter(n()>1))

答案 1 :(得分:0)

我首先要计算任何团队获得的奖牌数量,并将其从高到低排序,然后将数据集排在前10名。

medals_perteam <- sapply(split(medalWinner, medalWinner$Team), nrow)
medals_perteam <- sort(medals_perteam, decreasing = TRUE)
# Replace [1:3] by [1:10] for top 10 instead of top 3
topmedals <- medalWinner[medalWinner$Team %in% names(medals_perteam)[1:3],]

然后我们可以绘制此数据子集:

ggplot(data = topmedals, aes(x = Team, fill = Medal)) +
  geom_bar()