在ggplot2中使用`scale_fill_manual`手动着色图不起作用 [英] Manually colouring plots with `scale_fill_manual` in ggplot2 not working

查看:739
本文介绍了在ggplot2中使用`scale_fill_manual`手动着色图不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力手动更改ggplot2中的条形颜色.奇怪的是,当使用更复杂的格式需要图例时,通过使用scale_fill_manual并设置valueslabels等,我可以使它工作.但是当创建不需要图例的简单图表时,我似乎无法使其正常工作.以下是一个示例数据帧,我在dplyr中使用的获取百分比的步骤以及我认为它在ggplot2中应如何工作.我只想手动将条形颜色更改为红色,seagreen3和灰色.

I'm struggling with how to manually change bar colours in ggplot2. Strangely, I can get it to work when using more complicated formats that require a legend by using scale_fill_manual and setting the values,labels, etc. But when creating a simpler chart that doesn't require a legend, I can't seem to get it to work. Below is a sample data frame, the steps I used in dplyr to get the percentages, and how I think it should work in ggplot2. I just want to manually change the bar colours to red, seagreen3, and grey.

任何帮助将不胜感激.我也很想知道用于快速计算百分比的不同方法.我一直在使用dplyr进行管道传输,但是如果能很好地了解其他编写代码的方式,那将是一件很不错的事情.

Any help would be appreciated. I'm also curious to know different ways that are used to quickly calculate percentages. I've been using piping with dplyr, but if would be great to see other ways of writing code.

library(dplyr)
library(ggplot2)

Service <- c("Satisfied", "Dissatisfied", "Neutral", "Satisfied", "Neutral")
Service2 <- c("Dissatisfied", "Dissatisfied", "Neutral", "Satisfied", "Satisfied")

Services <- data.frame(Service, Service2)

ServicesProp <- Services %>%
                select(Service) %>% group_by(Service) %>% 
                summarise(count=n()) %>%
                mutate(percent = count / sum(count))

ggplot(ServicesProp, aes(x = Service, y = percent)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    scale_fill_manual(values = c("red", "seagreen3", "grey"))

推荐答案

以防万一,您不确定@baptise的含义是什么

Just in case you are not sure what @baptise means:

ggplot(ServicesProp, aes(x = Service, y = percent, fill = Service)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  scale_fill_manual(values = c("red", "grey", "seagreen3"))

这篇关于在ggplot2中使用`scale_fill_manual`手动着色图不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆