r语言 - GGplot 不会改变散点图的颜色,但会在其他图上改变颜色



我有一个脚本,可以从我的数据创建散点图和两个条形图。一切正常,除了当我尝试更改散点图的颜色时,它不起作用,它们仍然是标准颜色。

条形图

我想从条形图中获取红色和灰色(分别为 #f40009 和 #8e8f90),并用它们为散点图着色,但它不起作用。

有没有人知道为什么会发生这种情况以及如何解决?

散点图的代码如下:

lof <- 2
days <- 3
plot2 <-ggplot( data3, aes( CE11000_ERLOS, Z_UCS))+
geom_point(aes(colour=ifelse( data3$LOF>lof &  data3$Z_LAST_DAYS<days &  data3$CE11000_ERLOS>100,"#8e8f90","#f40009")), size = 3)+
labs(list(y = "Unit cases", x = "Gross sales revenue"))+
ggtitle(bquote(atop(.("Visualization of Outliers"), atop(italic(.(country)), ""))))+
scale_colour_discrete(guide = guide_legend(title = NULL), labels = c("Outliers", "Not outliers"))+
theme(plot.title = element_text(hjust = 0.5))+
geom_text(aes(label = ifelse( data3$LOF>lof &  data3$Z_LAST_DAYS<days,paste( data3$Z_CDOW, data3$CE11000_BUDAT2,sep = "n "),""),hjust=1.05,vjust=1), size = 3.5)+
scale_y_continuous(labels = comma)+
scale_x_continuous(labels = comma)
print(plot2)

数据是:

LOF  Z_LAST_DAYS CE11000_ERLOS Z_UCS  Z_CDOW    CE11000_BUDAT2
3.1  1           996789        21195  Thursday  20170126
1.01 23          11912948      210839 Wednesday 20170104
1.4  22          14322767      257269 Thursday  20170105
1.01 21          11817447      185197 Friday    20170106
1.66 18          7906971       153807 Monday    20170109

这是结果分散

在此行中

geom_point(aes(colour=ifelse( data3$LOF>lof & data3$Z_LAST_DAYS<days & data3$CE11000_ERLOS>100,"#8e8f90","#f40009")), size = 3)

通过将 Color 语句中输入的内容的级别放入aes调用中,将颜色的级别映射到(默认)颜色。

如果你把你的颜色声明从aes电话中剔除,你应该得到实际的颜色。

比较例如:

不是粉红色:

ggplot(iris, aes(Sepal.Width, Sepal.Length)) + 
geom_point(aes(colour="pink"))

粉红色:

ggplot(iris, aes(Sepal.Width, Sepal.Length)) + 
geom_point(colour="pink")

或者,在您的情况下:

geom_point(colour=ifelse( data3$LOF>lof &  data3$Z_LAST_DAYS<days &  data3$CE11000_ERLOS>100,"#8e8f90","#f40009"), size = 3)

或者,您可以使用scale_colour_manual根据 @Adam Quek 的注释更改默认颜色。

在 ggplot2 中更改默认颜色的示例代码

data <- iris[iris$Species == "setosa" | iris$Species == "virginica", c(1:2,5)]
levels(data$Species)
droplevels(data$Species)
data
plot <- ggplot(data, aes(x = Sepal.Length, y = Sepal.Width)) + 
geom_point(aes(color = Species))

下图生成默认颜色

plot 

使用默认颜色打印

您可以添加scale_color_manual()以更改默认颜色

plot + scale_color_manual(
values=c("setosa" = "darkgrey","virginica" = "red"))

使用自定义颜色绘制

最新更新