2016-07-06 38 views
0

这里是我使用的数据和代码:ggplot不创建一个传说,当变量数值

str(dfrev_benchmark2) 
'data.frame': 20 obs. of 2 variables: 
$ B_Vec : num 1 51 101 151 201 251 301 351 401 451 ... 
$ revenue: num 31508 1606929 3182350 4757771 6333192 ... 

str(dfaugrev2) 
'data.frame': 20 obs. of 2 variables: 
$ B_Vec : num 1 51 101 151 201 251 301 351 401 451 ... 
$ revenue: num 45451 2317977 4590503 6863029 9135556 ... 

str(dfjanrev2) 
'data.frame': 20 obs. of 2 variables: 
$ B_Vec : num 1 51 101 151 201 251 301 351 401 451 ... 
$ revenue: num 18412 939015 1859618 2780220 3700823 ... 

profitmonthly <- ggplot() + 
geom_line(data=dfjanrev2, aes(x=dfjanrev2[,1], y=dfjanrev2[,2]), 
     color="#000666", size=1.3)+ 
geom_line(data=dfaugrev2, aes(x=dfaugrev2[,1], y=dfaugrev2[,2]), 
     color="#990033", size=1.3)+ 
geom_line(data=dfrev_benchmark2, aes(x=dfrev_benchmark2[,1], y=dfrev_benchmark2[,2]), 
     color="#006633", size=1.3)+ 
scale_y_continuous(labels = scales::dollar)+ 
scale_x_continuous(limits = c(0, 1000))+ 
xlab("Size of the battery")+ 
ylab("Profit") + 
ggtitle("Size of the Battery vs Profit: Monthly Forecast Timespan") + 
theme(plot.title=element_text(size = 15, face="bold"), axis.text=element_text(size=12), 
    axis.title=element_text(size=12,face="bold"))+ 
scale_color_manual(name = "Line Color", 
        labels = c("January"="#000666", "August"="#990033", "Yearly forecast"="#006633")) 


print(profitmonthly) 

它给了我这个阴谋:

enter image description here

我曾尝试将颜色置于aes之内,但是该图是空的并且不读取数据。所以我猜这里scale_color_manual没有用,因为数据不是因素。

我只需要创建一个描述线条颜色的简单图例。

回答

0

您需要将它全部放在一个单独的数据框中,并在aes内部传递颜色参数。

dfjanrev2$month <- "January" 
dfaugrev2$month <- "August" 
dfrev_benchmark2$month <- "Yearly forecast" 
data <- rbind(dfjanrev2, dfaugrev2, dfrev_benchmark2) 

profitmonthly <- ggplot(data) + 
    geom_line(aes(x=B_Vec, y=revenue, color = month), size=1.3)+ 
    scale_y_continuous(labels = scales::dollar)+ 
    scale_x_continuous(limits = c(0, 1000))+ 
    xlab("Size of the battery")+ 
    ylab("Profit") + 
    ggtitle("Size of the Battery vs Profit: Monthly Forecast Timespan") + 
    theme(plot.title=element_text(size = 15, face="bold"), axis.text=element_text(size=12), 
    axis.title=element_text(size=12,face="bold"))+ 
    scale_color_manual(name = "Line Color", 
        values = c("January"="#000666", 
          "August"="#990033", 
          "Yearly forecast"="#006633")) 

编辑:将labels改为values

+0

该工作,也将'标签'更改为'值',否则会导致错误。 非常感谢! – DariaOs

+0

对,我编辑了答案。换句话说,还有其他方法可以强制使用多个'geom_lines'的图例,但通常不推荐使用,请查看第二个答案:http://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-线积 – Choubi