首页 文章

颜色/线条标签在ggplot中按字母顺序排序 . 怎么避免?

提问于
浏览
0

我正在尝试从同一图表上的数据集中绘制3行,并使用ggplot2显示它们 . 我想手动设置每行的颜色和形状 .

问题是颜色/形状是根据标签的词典顺序设置的,我似乎对所选择的内容没有任何控制 .

这就是我尝试过的:

px <- 
    ggplot(dataset) + 
    stat_smooth(aes(x=id, y=dataset[,4], colour="2000",  linetype="2000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
    stat_smooth(aes(x=id, y=dataset[,3], colour="500",  linetype="500"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
    stat_smooth(aes(x=id, y=dataset[,2], colour="1000", linetype="1000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +    
    theme(legend.title=element_blank()) +
    xlab("x") +
    ylab("y") +
    ggtitle("px") 

py <- 
    ggplot(dataset) + 
    stat_smooth(aes(x=id, y=dataset[,4], colour="1000",  linetype="1000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
    stat_smooth(aes(x=id, y=dataset[,3], colour="500",  linetype="500"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
    stat_smooth(aes(x=id, y=dataset[,2], colour="2000", linetype="2000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +    
    theme(legend.title=element_blank()) +
    xlab("x") +
    ylab("y") +
    ggtitle("py") 
pz <- 
    ggplot(dataset) + 
    stat_smooth(aes(x=id, y=dataset[,4], colour="B1000",  linetype="B1000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
    stat_smooth(aes(x=id, y=dataset[,3], colour="C500",  linetype="C500"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
    stat_smooth(aes(x=id, y=dataset[,2], colour="A2000", linetype="A2000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +    
    theme(legend.title=element_blank()) +
    ylab("y") +
    xlab("x") +
    ggtitle("pz")

这就是我得到的:

enter image description here

我的数据如下:

> head(dataset)
  id  A  B  C
1  1  0 26 44
2  2  0  0  0
3  3  0  0 46
4  4 26 22  0
5  5 16  0  0
6  6  0  0 30

我希望有一些像最后一样的东西,在图例框上有这些确切的颜色,形状和排序,但不必在每个标签前放置ABC .

我怎样才能做到这一点?

PS:即使我使用stat_smooth,geom_line也是如此

1 回答

  • 5

    你的问题是因为这不是 ggplot2 中的事情 . 如果你在 aes() 内使用了 [ ,那么's a sure sign that you'做错了 .

    我们融合数据框,然后将变量映射到美学,而不是对单个 geom 进行三次单独调用 .

    dat <- read.table(text = "  id  A  B  C
     1  1  0 26 44
     2  2  0  0  0
     3  3  0  0 46
     4  4 26 22  0
     5  5 16  0  0
     6  6  0  0 30",header = TRUE,sep = "")
    
    require(reshape2)
    datm <- melt(dat,id.vars = 'id')
    datm$variable <- factor(datm$variable,levels = c('C','A','B'))
    
    ggplot(datm) + 
        geom_line(aes(x = id,y = value,colour = variable,linetype = variable))
    

    我在这里使用了 geom_line 因为您的样本数据太小而无法使用 geom_smooth ,但它的工作方式相同 . 一旦融化了数据,就可以通过调整因子级别的顺序来控制顺序 .

    当然,您可以随时将级别更改为 A 到_1839364之外的其他级别 .

相关问题