如何将R ggplot2中geom_bar的颜色统一设置为#0277BD?
问题:如何将ggplot柱状图统一设置为单一颜色#0277BD?
我尝试把柱状图所有柱子的颜色统一设为#0277BD,用scale_fill_manual(values=c("#0277BD"))时出现错误:
Error in `f()`: ! Insufficient values in manual scale. 24 needed but only 1 provided.
改用scale_fill_brewer(palette="Blues")又得到警告:
Warning message: In RColorBrewer::brewer.pal(n, pal) : n too large, allowed maximum for palette Blues is 9 Returning the palette you asked for with that many colors
数据
df = structure(list(CITYNAME = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "w", "x", "y", "z"), AvgTMin = c(20.28, 20.38, 20.08, 20.35, 20.38, 20.76, 21, 21.21, 20.45, 20.21, 21.18, 20.29, 20.61, 20.44, 20.95, 19.75, 20.58, 20.32, 21.05, 20.28, 20.09, 20.15, 20.73, 20.12)), row.names = c(NA, -24L), class = c("tbl_df", "tbl", "data.frame"))
当前代码
# 转换为华氏度绘图 df %>% mutate(AvgTMin = AvgTMin * (1.8) + 32) %>% # 从摄氏度转华氏度 ggplot(aes(x = reorder(CITYNAME,AvgTMin), y = AvgTMin, fill = CITYNAME)) + geom_bar(stat="identity") + coord_cartesian(ylim = c(60,70.3)) + theme(axis.text = element_text(size = 14)) + geom_text(aes(label=sprintf("%0.2f", AvgTMin)), vjust=-0.2, size = 4) + labs(x = NULL, y = "平均最低温度 °F") + theme(axis.text.x = element_text(angle = 90), legend.position = 'none') + ggtitle("1980-2021 各城市温度趋势")
解决方案
问题核心是你在aes里把fill映射到了CITYNAME,ggplot会默认给每个不同城市分配独立颜色。要统一颜色,有两种简单方法:
方法1:移除fill映射,直接在geom_bar中设置颜色
删掉aes里的fill = CITYNAME,在geom_bar中直接指定填充色,这是最直接的方式:
df %>% mutate(AvgTMin = AvgTMin * (1.8) + 32) %>% ggplot(aes(x = reorder(CITYNAME,AvgTMin), y = AvgTMin)) + geom_bar(stat="identity", fill = "#0277BD") + # 直接设置统一填充色 coord_cartesian(ylim = c(60,70.3)) + theme(axis.text = element_text(size = 14)) + geom_text(aes(label=sprintf("%0.2f", AvgTMin)), vjust=-0.2, size = 4) + labs(x = NULL, y = "平均最低温度 °F") + theme(axis.text.x = element_text(angle = 90), legend.position = 'none') + ggtitle("1980-2021 各城市温度趋势")
方法2:保留fill映射,重复单一颜色匹配类别数量
如果需要保留fill的映射(比如后续有扩展需求),可以用rep()函数让scale_fill_manual为所有城市重复同一个颜色:
df %>% mutate(AvgTMin = AvgTMin * (1.8) + 32) %>% ggplot(aes(x = reorder(CITYNAME,AvgTMin), y = AvgTMin, fill = CITYNAME)) + geom_bar(stat="identity") + coord_cartesian(ylim = c(60,70.3)) + theme(axis.text = element_text(size = 14)) + geom_text(aes(label=sprintf("%0.2f", AvgTMin)), vjust=-0.2, size = 4) + labs(x = NULL, y = "平均最低温度 °F") + theme(axis.text.x = element_text(angle = 90), legend.position = 'none') + ggtitle("1980-2021 各城市温度趋势") + scale_fill_manual(values = rep("#0277BD", nrow(df))) # 重复颜色匹配城市数量
内容的提问来源于stack exchange,提问作者Ed_Gravy
相关产品推荐
相关产品推荐

