我很难设置图例并在重叠的直方图中更改颜色。 出于某种原因,当我尝试更改颜色时,图例不再自定义。 这是没有任何颜色规格的代码,你能帮帮我吗?
# 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
当我添加它时,有问题的一行会删除图例中的所有格式: scale_fill_manual(values = c(&#34;#0000FF&#34;,&#34;#FF0000&#34;))
最后一个问题,我喜欢图形,但是,ggplot2的默认颜色应该颠倒(浅蓝色,粉红色第二),有没有办法做到这一点?我无法在互联网上的任何地方找到默认颜色的十六进制代码。
基于Henrik的回复的正确代码
# 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') +
scale_fill_manual(values=c("#0000FF", "#FF0000"),
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
这是如何在第一张图中访问ggplot使用的2种颜色:
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 :-)