简体   繁体   English

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

[英]ggplot2 change colours in bar chart with scale_color_identity()

I'm using the workaround to remove diagonal lines from a ggplot legend: https://groups.google.com/forum/?fromgroups=#!topic/ggplot2/vJnF9_HBqx4 我正在使用解决方法从ggplot图例中删除对角线: https ://groups.google.com/forum/ fromgroups = #!topic /ggplot2 / vJnF9_HBqx4

With the following data, how do I change the colours of the groups? 使用以下数据,如何更改组的颜色?

# 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))

I have tried changing the following elements : 我试过更改以下元素:

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"))

but each produces an error. 但每个都会产生错误。

Try this. 尝试这个。 The guides call let's you pick which scale to not have a legend. 指南调用让你选择哪个刻度没有图例。 And, you can set the outline colour without aes(). 并且,您可以在没有aes()的情况下设置轮廓颜色。

EDIT after comment about diagonal line in legend 关于传奇中对角线的评论后编辑

Based on this SO question remove diagonal line in legend , you can added the guides(fill etc. call to remove the diagonal. 基于此SO问题删除图例中的对角线 ,您可以添加指南(填充等调用以删除对角线。

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)

在此输入图像描述

You can also call geom_bar twice. 您也可以两次调用geom_bar Once for the legend, and without the color argument, and once with the color argument but suppressing the legend 一次用于图例,没有颜色参数,一次用颜色参数但是压制图例

 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') )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM