ggplot2 使用 scale_color_identity() 更改条形图中的颜色

ggplot2 change colours in bar chart with scale_color_identity()

我正在使用解决方法从 ggplot 图例中删除对角线:https://groups.google.com/forum/?fromgroups=#!topic/ggplot2/vJnF9_HBqx4

有了以下数据,如何更改组的颜色?

# Create data #

a<-as.data.frame(c(1,1,1,2,2))
b<-as.data.frame(c("A","A","B","B","A"))
c<-as.data.frame(c(20,20,60,50,50))
a<-cbind(a,b,c)
colnames(a)<-c("X","Gp","Y")

# Plot #

ggplot(a, aes(x=X, y=Y,fill=Gp)) + 
  geom_bar(stat = "identity", aes(colour = "black")) + 
  scale_color_identity() + 
  theme(legend.key = element_rect(colour = "black", size = 1))

我尝试更改以下元素:

scale_color_identity(values=c("red","yellow"))

geom_bar(stat = "identity", aes(colour = c("red","yellow")))

geom_bar(stat = "identity", aes(colour = "black"), fill=c("red","yellow"))

但每个都会产生错误。

试试这个。向导让您选择没有图例的比例。而且,你可以不使用 aes() 来设置轮廓颜色。

在评论图例中的对角线后进行编辑

基于这个 SO 问题 remove diagonal line in legend,您可以添加参考线(填充等调用以删除对角线。

ggplot(a, aes(x=X, y=Y,fill=Gp)) + 
  geom_bar(stat = "identity", colour = "black") + 
  scale_fill_manual(values = c("red","yellow")) +
  guides(fill = guide_legend(override.aes = list(colour = NULL))) +
  guides(colour = FALSE)

您还可以调用 geom_bar 两次。一次用于图例,没有颜色参数,一次有颜色参数但抑制图例

 ggplot(a, aes(x=X, y=Y,fill=Gp)) + 
       geom_bar(stat = "identity", color = 'black', show_guide = F) +
       geom_bar(stat = 'identity') + 
       scale_fill_manual(values = c('red', 'yellow') )