R 自定义ggplot2重叠密度图中的图例和颜色
我很难建立一个图例,也很难改变叠加直方图中的颜色。 由于某种原因,当我尝试改变颜色时,图例不再是定制的。 这是没有任何颜色说明的代码,你能帮我吗R 自定义ggplot2重叠密度图中的图例和颜色,r,colors,ggplot2,overlay,R,Colors,Ggplot2,Overlay,我很难建立一个图例,也很难改变叠加直方图中的颜色。 由于某种原因,当我尝试改变颜色时,图例不再是定制的。 这是没有任何颜色说明的代码,你能帮我吗 # o - o - o Preparing data o - o - o - o - o - o - o - o - o iris$Petal.Length.binary <- NA iris$Petal.Length.binary[iris$Petal.Length < 4.5] <- "low length"
# o - o - o Preparing data o - o - o - o - o - o - o - o - o
iris$Petal.Length.binary <- NA
iris$Petal.Length.binary[iris$Petal.Length < 4.5] <- "low length"
iris$Petal.Length.binary[iris$Petal.Length >= 4.5] <- "high length"
iris$Petal.Length.binary <- factor(iris$Petal.Length.binary, levels=c("low length", "high length"))
# o - o - o Density plot o - o - o - o - o - o - o - o - o
Density <- ggplot(iris, aes(Sepal.Length, fill = Petal.Length.binary))
Density2 <-
(Density +
#_____________Change colour density___________
geom_density(alpha = 0.3) +
#_____________Position the legend in bottom left___________
theme(legend.justification=c(0,1), legend.position=c(0,1)) +
#_____________Customising title___________ http://www.cookbook-r.com/Graphs/Titles_(ggplot2)/
ggtitle('Title : Example Plot') +
theme(plot.title = element_text(lineheight=0.9, face="bold")) +
#_____________Labels___________
labs(x='Sepal Length', y='Probability Density') +
#_____________Customising legend___________
scale_fill_discrete(name = "An irrelevant \nlegend title",
breaks=c("low length", "high length"),
labels=c("Low \nlength", "High \nlength")) +
#_____________Increase spacing in legend categories___________
theme(legend.key.height=unit(1.5,"line")) +
theme(legend.key.width=unit(1.2,"line")) )
Density2
添加时会从图例中删除所有格式的问题行是:
刻度\填充\手动值=c0000FF,FF0000
最后一个问题,我喜欢这张图,但是ggplot2的默认颜色应该先是淡蓝色,然后是粉色,有没有办法呢?我在互联网上找不到默认颜色的十六进制代码
根据Henrik的回答更正代码
这是如何获得ggplot在第一张图中使用的两种颜色:
gg_color_hue <- function(n) {
hues = seq(15, 375, length=n+1)
hcl(h=hues, l=65, c=100)[1:n]
}
n = 2
cols = gg_color_hue(2)
str(cols) # the hex numbers :-)
添加刻度填充手动密度2+刻度填充手动值=c0000FF时,FF0000将生成一条警告消息:“填充”刻度已存在。为“填充”添加另一个比例,该比例将替换现有比例。。你能解释一下警告信息中你不明白的地方吗?请同时阅读?刻度填充手册。在“参数”部分,您可以使用常见的离散比例参数:名称、分隔符、标签。谢谢,您是对的。一旦我将图例自定义的所有参数添加到“刻度填充”手册中,我会保留自定义图例和新颜色。刻度\u填充\u手动值=c0000FF,FF0000,名称=不相关的标题\n分隔符=clow长度,高长度,标签=clow长度,高\n长度我想知道您是否知道如何反转ggplot使用的绘图的默认颜色。一种可能性是反转颜色向量。确实,非常感谢您,我将用答案更新我的回答
gg_color_hue <- function(n) {
hues = seq(15, 375, length=n+1)
hcl(h=hues, l=65, c=100)[1:n]
}
n = 2
cols = gg_color_hue(2)
str(cols) # the hex numbers :-)