gpt4 book ai didi

r - 带有中断的ggplot scale_color_manual与预期顺序不匹配

转载 作者:行者123 更新时间:2023-12-03 15:24:47 24 4
gpt4 key购买 nike

我正在绘制散点图,我想指定图例中文本的顺序以及颜色。使用ggplot,颜色顺序与编写的文本顺序不匹配。

我的代码:

MyX<-c(1,2,3,4,5)
MyY<-c(3,4,5,2,7)
MyCat<-c("Dark","Medium","DarkLight","LightDark","Light")
MyDF<-data.frame(MyX,MyY,MyCat)


ggplot(MyDF, aes(x=MyX, y=MyY, color=MyCat)) +
geom_point()+
xlab("Time") +
ylab("Num") +
scale_color_manual(breaks = c("Dark","DarkLight","Medium","LightDark","Light"),
values=c("red", "orange","yellow","cadetblue2","dodgerblue"))

我不希望图例中文本的默认顺序,因此我想将顺序更改为:

“暗”,“暗光”,“中”,“浅暗”,“浅”

我还希望颜色在渐变中:

“红色”,“橙色”,“黄色”,“cadetblue2”,“dodgerblue”

这样Dark =红色,DarkLight =橙色,Medium =黄色,LightDark = cadetblue2,Light =蓝色。

我以为上面的代码会发生这种情况。但是,如图所示,文本与颜色不匹配,我有:

深色=红色,深色=橙色,中=蓝色,浅深色= cadetblue2,浅=黄色。

注意-使用色带时,我有同样的问题:
  gs.pal <- colorRampPalette(c("red","blue"),bias=.1,space="rgb")
+scale_color_manual(breaks = c("Dark","DarkLight","Medium","LightDark","Light"),
values=gs.pal(5))

最佳答案

ggplot为了避免这种情况,按字母顺序排列MyCat变量,需要按所需顺序将该变量定义为一个因子:

library(ggplot2)

MyDF<-data.frame(MyX,MyY,MyCat)

#define as factor in the desired order
MyDF$MyCat<-factor(MyDF$MyCat, levels=c("Dark","DarkLight","Medium","LightDark","Light"))

ggplot(MyDF, aes(x=MyX, y=MyY, color=MyCat)) +
geom_point()+
xlab("Time") +
ylab("Num") +
scale_color_manual(breaks = c("Dark","DarkLight","Medium","LightDark","Light"),
values=c("red", "orange","yellow","cadetblue2","dodgerblue"))

这应该提供欲望的顺序
enter image description here

关于r - 带有中断的ggplot scale_color_manual与预期顺序不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54078772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com