将图例添加到ggplot2 + ggfortify时出现问题

时间:2017-11-19 15:32:14

标签: r ggplot2 legend ggfortify

我遇到麻烦

scale_colour_manual 

ggplot的功能。我试过了

guide = "legend" 

强制传奇出现,但它不起作用。代码:

library(ggfortify)
library(ggplot2)
p  <- ggdistribution(pgamma, seq(0, 100, 0.1), shape = 0.92, scale = 22, 
                     colour = 'red')
p2 <- ggdistribution(pgamma, seq(0, 100, 0.1), shape = 0.9, scale = 5, 
                     colour = 'blue', p=p)

p2 + 
theme_bw(base_size = 14) +
theme(legend.position ="top") +
xlab("Precipitación") +
ylab("F(x)") +
scale_colour_manual("Legend title", guide = "legend", 
                      values = c("red", "blue"), labels = c("Observado","Reforecast")) +
ggtitle("Ajuste Gamma")

enter image description here

2 个答案:

答案 0 :(得分:1)

stat_function的解决方案:

library(ggplot2)
library(scales)

cols <- c("LINE1"="red","LINE2"="blue")
df <- data.frame(x=seq(0, 100, 0.1))
ggplot(data=df, aes(x=x)) + 
stat_function(aes(colour = "LINE1"), fun=pgamma, args=list(shape = 0.92, scale = 22)) +
stat_function(aes(colour = "LINE2"), fun=pgamma, args=list(shape = 0.9, scale = 5)) +
theme_bw(base_size = 14) +
theme(legend.position ="top") +
xlab("Precipitación") +
ylab("F(x)") +
scale_colour_manual("Legend title", values=c(LINE1="red",LINE2="blue"),
                    labels = c("Observado","Reforecast")) +
scale_y_continuous(labels=percent) +
ggtitle("Ajuste Gamma")

enter image description here

答案 1 :(得分:0)

这似乎是ggfortify的错误。*尽管您可以使用geom_line()中的ggplot2来获得相同的结果,但是:

library(ggplot2)

# Sequence of values to draw from dist(s) for plotting
x = seq(0, 100, 0.1)

# Defining dists
d1 = pgamma(x, shape=0.92, scale=22)
d2 = pgamma(x, shape=0.90, scale=5)

# Plotting
p1 = ggplot() +
     geom_line(aes(x,d1,colour='red')) + 
     geom_line(aes(x,d2,colour='blue')) + 
     
     theme_bw(base_size = 14) +
     theme(legend.position="top") +

     ggtitle("Ajuste Gamma") +
     xlab("Precipitación") +
     ylab("F(x)") +
     
     scale_colour_manual("Legend title", 
                         guide = "legend", 
                         values = c("red", "blue"), 
                         labels=c("Observado", "Reforecast"))

Results figure


*相关问题:Plotting multiple density distributions on one plot