在barplot ggplot2中个性化每个面上的填充颜色

问题描述 投票:1回答:1

我想在一个方面制作一个情节。

enter image description here

library(ggplot2)
library(dplyr)

mtcars0 = mtcars %>% group_by(cyl) %>% mutate(MeanMpg = round(mean(mpg), 2))

p <- ggplot(mtcars0, aes(mpg, wt)) + 
  geom_bar(stat = "identity", width = 2) + 
  facet_grid(~ cyl ~. ) + 
  geom_text(aes(mpg, wt, label = MeanMpg), size = 4, x = 15, y = 5)

问题是当我尝试根据每个方面(1个方面1色)个性化色条。

p <- ggplot(mtcars0, aes(mpg, wt, fill = cyl)) + 
  geom_bar(stat = "identity", width = 2) + 
  facet_grid(~ cyl ~. ) + 
  geom_text(aes(mpg, wt, label = MeanMpg), size = 4, x = 15, y = 5) +
  scale_fill_manual(values = c("royalblue", "orange", "orangered"))
p

我怎么能填满我的酒吧?

r ggplot2
1个回答
1
投票

您需要使用factor类而不是double类填充条形。您可以将cyl列转换为具有as.factor()函数的因子:

p <- ggplot(mtcars0, aes(mpg, wt, fill = as.factor(cyl))) + 
  geom_bar(stat = "identity", width = 2) + 
  facet_grid(~ cyl ~. ) + 
  geom_text(aes(mpg, wt, label = MeanMpg), size = 4, x = 15, y = 5) +
  scale_fill_manual(values = c("royalblue", "orange", "orangered"))
p

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.