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)
它给了我这个阴谋:
我曾尝试将颜色置于aes
之内,但是该图是空的并且不读取数据。所以我猜这里scale_color_manual
没有用,因为数据不是因素。
我只需要创建一个描述线条颜色的简单图例。
该工作,也将'标签'更改为'值',否则会导致错误。 非常感谢! – DariaOs
对,我编辑了答案。换句话说,还有其他方法可以强制使用多个'geom_lines'的图例,但通常不推荐使用,请查看第二个答案:http://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-线积 – Choubi