使用g中的ggplot2更改geom_bar中的条形图颜色

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

我有以下内容,以条形图数据框。

c1 <- c(10, 20, 40)
c2 <- c(3, 5, 7)
c3 <- c(1, 1, 1)
df <- data.frame(c1, c2, c3)
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
  geom_bar(stat="identity", width=c2) +
  scale_fill_manual(values=c("#FF6666"))

我最终只有灰色条:Grey bars for bar plot

我想改变酒吧的颜色。我已经尝试过来自http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/的不同scale_fill_manual,但仍然有灰色条。

谢谢您的帮助。

r ggplot2 colors geom-bar
1个回答
47
投票

如果你想让所有的条形颜色都相同(fill),你可以轻松地将它添加到geom_bar中。

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

fill = the_name_of_your_var中添加aes以根据变量更改颜色:

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

如果要手动更改颜色,请使用scale_fill_manual()

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

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