R语言 具有ggplot和自定义颜色的条形图

6yoyoihd  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(156)

我有这张table

我想用ggplot做一个条形图,并为每个条形图定制颜色。为此,我从以下代码开始:

ggplot(GoalsAndFouls, aes(x = name, y = goals)) +
      labs(x = "Leagues", y = "Goals") +
      geom_bar(stat = "identity")

我试着用下面的代码添加颜色,但是颜色没有改变。

ggplot(GoalsAndFouls, aes(x = name, y = goals)) +
      labs(x = "Leagues", y = "Goals") +
      geom_bar(stat = "identity") +
      scale_fill_manual(values = c("red", "green", "blue", "grey", "orange")) +
      theme(legend.position="none")

我能不能把犯规作为每个联赛的一个附加标准?

pdkcd3nj

pdkcd3nj1#

因为已经指定了颜色和颜色的顺序,所以只需要将fill = name添加到aes()

library(tidyverse)
name <- c("Serie A", "Premier League", "La Liga", "Ligue 1", "Bundesliga")
goals <- c(7476, 7213, 7072, 6656, 6324)
fouls <- c(74232, 57506, 73053, 67042, 56720)
GoalsAndFouls <- data.frame(name, goals, fouls)

ggplot(GoalsAndFouls, aes(x = name, y = goals, fill = name)) +
  labs(x = "Leagues", y = "Goals") +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = c("red", "green", "blue", "grey", "orange")) +
  theme(legend.position="none")

相关问题