R匹配ggplot中的图例颜色

时间:2014-08-20 09:03:47

标签: r ggplot2

基于此代码:

ggplot(inputR_performances, aes(x=reorder(X,MCCHVAR))) + 
  geom_point(aes(y=MCCGS, col="chartreuse4")) +
  geom_point(aes(y=MCCHVAR, col="cyan2")) +
  geom_point(aes(y=MCCHDIV, col="cornflowerblue")) +
  geom_smooth(aes(y=MCCHVAR, group=1), method="loess", se=FALSE, col="cyan2") + 
  geom_smooth(aes(y=MCCHDIV, group=1), method="loess", se=FALSE, col="cornflowerblue") + 
  geom_smooth(aes(y=MCCGS, group=1), method="loess", se=FALSE, col="chartreuse4") +
  panel.configuration

这给出了: enter image description here 我应该改变什么:

  1. 点出现在预期的(自定义)颜色而不是粉红色 - 绿色 - 蓝色默认值?
  2. 图例标签是“MCC ..”而不是“chartreuse4 ...”?
  3. 首先,我尝试将col=...放在aes geom_point之外,就像它出现在geom_smooth中一样。这给了正确的颜色,但没有显示传奇。感谢。

    更新:@beetroot评论后:

    起始数据:包含4列的数据帧(一个用于X,3个用于Y:X [因子],MCCGS [数字],MCCHVAR [数字],MCCHDIV [数字]):

    colnames(df1input) <- c("X","MCCGS","MCCHVAR","MCCHDIV")    
    

    我使用融合函数将其更改为3列数据框,以便所有数值都在一列(名为“value”的列)中,列(“变量”)表示它是来自MCCHVAR,MCCHDIV等。 / p>

    df1input_m <- melt(df1input, id="X") 
    
    str(df1input_m)
    'data.frame':   204 obs. of  3 variables:
     $ X       : Factor w/ 68 levels "O00255","O15118",..: 1 2 3 4 5 6 7 8 9 10 ...
     $ variable: Factor w/ 3 levels "MCCGS","MCCHVAR",..: 1 1 1 1 1 1 1 1 1 1 ...
     $ value   : num  0.78 0.49 0.83 0.69 0.74 0.54 0.48 0.57 0.69 0.84 ...
    

2 个答案:

答案 0 :(得分:1)

根据颜色,我猜你只是将颜色添加到ggplot命令中,所以像ggplot(data, aes(x=X, y=value, color=variable))+geom_point()+geom_smooth()这样的东西应该做你想要的。

例如,可以使用比例参数更改图例标题:scale_colour_discrete(name="legend title")

我不确定,但也许sjPlot-packagesjp.scatter功能也可以做你想做的事情(见an example here)。

答案 1 :(得分:0)

添加&#34; col&#34;在美学中,只有当你想用变量给它上色时才有效。从当前代码中删除颜色命令也会使图例名称恢复为默认值。

对于点的着色,只需将col移出aes部分即可。这段代码应该适合你:

ggplot(inputR_performances, aes(x=reorder(X,MCCHVAR))) + 
  geom_point(col="chartreuse4", aes(y=MCCGS)) +
  geom_point(col="cyan2", aes(y=MCCHVAR)) +
  geom_point(col="cornflowerblue", aes(y=MCCHDIV)) +
  geom_smooth(col="cyan2", aes(y=MCCHVAR, group=1), method="loess", se=FALSE) + 
  geom_smooth(col="cornflowerblue", aes(y=MCCHDIV, group=1), method="loess", se=FALSE) + 
  geom_smooth(col="chartreuse4", aes(y=MCCGS, group=1), method="loess", se=FALSE) +
  panel.configuration

基本上,你的问题实际上是没有出现传奇。尝试查找出现此问题的其他SO主题(例如ggplot2: how to show the legendMissing legend with ggplot2 and geom_lineAdd legend to ggplot2 line plot),或创建新主题

相关问题