个性化条形图ggplot2中每个面上的填充颜色

时间:2019-02-14 03:16:01

标签: r ggplot2

我想在刻面中绘制小图。

enter image description here

<img src="" name="changepic" id="changepic">
    <select name="allseasons" id="allseasons">
        <option value="spring">Spring</option>
        <option value="summer">Summer</option>
        <option value="fall">Fall</option>
        <option value="winter">Winter</option>
    </select>

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

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 个答案:

答案 0 :(得分: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