要添加到由 www 回答 https://stackoverflow.com/a/46625724/7662668,我发现如果您不为颜色名称创建美观的映射,则可以节省很多混淆的风险。相反,使用有意义的标签,例如"mean"
为平均线。这样,如果您以后改变了对颜色选择的想法,您就不会得到诸如映射的手动比例之类的荒谬的东西"blue"
to "orange"
.
一般来说,美学映射不应该直接映射到颜色,而是应该分配values稍后将映射到颜色(手动或自动)。
EDIT:
根据 bdemarest 的建议,我添加了一些更多的解释和代码。这是 www 对 OP 代码的重构:
library("distr")
library("ggplot2")
#calculations
Percent_values <- c(0.5,0.75,0.9,0.95,0.995,0.999)
Dist1_mean = 20219
Dist1_CV = 3235 / 20219
Dist1_SDEV <- Dist1_mean*Dist1_CV
Dist1_parm2 <- sqrt(log(1+Dist1_CV^2))
Dist1_parm1 <- log(Dist1_mean)-(Dist1_parm2^2)/2
Dist1_quant <- qlnorm(Percent_values, meanlog=Dist1_parm1,
sdlog=Dist1_parm2)
lowerx <- 0
upperx <- 1.1*Dist1_quant[6]
mean_yvalue <- plnorm(Dist1_mean, meanlog=Dist1_parm1,
sdlog=Dist1_parm2)
perc <- 0.75
p75 <- Dist1_quant[2]
perc2 <- 0.995
p995 <- Dist1_quant[6]
#plot
ggplot(data.frame(x = c(lowerx, upperx)), aes(x = x))+
stat_function(fun=plnorm,
args=list(meanlog=Dist1_parm1,
sdlog=Dist1_parm2),
geom="line",
aes(colour="logn"), # logn label
size=1.25) +
scale_x_continuous(name="Value")+
scale_y_continuous(name="Cumulative probability") +
geom_segment(aes(x=Dist1_mean, y=0,
xend=Dist1_mean,
yend=mean_yvalue,
colour="mean"), # mean label
size=1.25) +
geom_segment(aes(x=0, y=mean_yvalue,
xend=Dist1_mean,
yend=mean_yvalue,
colour="mean"), # mean label
size=1.25, linetype="dotted",
show.legend = FALSE) +
geom_segment(aes(x=p75, y=0,
xend=p75, yend=perc,
colour="75th"), # 75th percentile label
size=1.25) +
geom_segment(aes(x=0, y=perc, xend=p75,
yend=perc,
colour="75th"), # 75th percentile label
size=1.25, linetype="dotted",
show.legend = FALSE) +
geom_segment(aes(x=p995, y=0, xend=p995,
yend=perc2,
colour="995th"), # 99.5th percentile label
size=1.25) +
geom_segment(aes(x=0, y=perc2, xend=p995,
yend=perc2,
colour="995th"), # 99.5th percentile label
size=1.25, linetype="dotted",
show.legend = FALSE) +
ggtitle("Cumulative density function of estimated future claims outgo") +
scale_colour_manual(name="",
# labels map onto colors and pretty labels
values=c("logn"="blue",
"mean"="red",
"75th"="green",
"995th"="orange"),
labels=c("logn"="Lognormal",
"mean"="Mean",
"75th"="75th %ile",
"995th"="99.5th %ile"))
请注意,在aes
映射、颜色名称已替换为描述性标签(例如,"red"
became "mean"
and "blue"
became "logn"
),以及scale_colour_manual
调用已更改为将这些标签映射到图例的颜色和漂亮标签上。这样,如果您稍后决定将第 75 个百分位段设为紫色而不是绿色,则只需更改颜色映射scale_colour_manual
在底部调用——您不必深入研究代码并找到正确的geom_segments
去改变,而且,如果你懒得这样做,你最终不会遇到可怕的事情,比如:
scale_colour_manual(values=c("blue"="blue",
"red"="red",
"green"="purple", # !!!???
"orange"="orange"))
相反,您(非常直观地)更改了颜色75th
变为紫色的组件:
scale_colour_manual(values=c("logn"="blue",
"mean"="red",
"75th"="purple", # makes sense
"995th"="orange"))
更改代码以在美学映射中使用有意义的标签只会使其更清晰、更直观、更易于阅读和维护。它不会改变图表的最终输出:
但是,如果您打算尝试绘制包含大量组件和信息丰富的图例的复杂图表,那么这只是习惯上的一个小改变,可能会在以后为您节省大量的挫败感。