[英]Legend in R plot that has kernel density, normal density and a histogram?
我目前是R的初学者,并且对如何为正在处理的三个地块插入图例有疑问。 我正在使用称为Iris的R上的内置数据集。 为了使图例出现,我有一些不足之处,我认为应该起作用,但事实并非如此,因为只有图出现。 我已附上以下地块的图像。 有人可以告诉我我需要怎么做才能使图例出现在相应的情节上? 先感谢您。
setosa_length <- iris$Sepal.Length[iris$Species == "setosa"]
hist(setosa_length, freq=FALSE)
x <- seq(4, 8, length.out=100)
y <- with(iris, dnorm(x, mean(setosa_length), sd(setosa_length)))
lines(x, y, col="red")
lines(density(setosa_length), col="blue")
legend(1, 95, legend=c("Normal Density", "Kernel Density"), col=c("red",
"blue"), lty=1:2, cex=0.5)
versicolor_length <- iris$Sepal.Length[iris$Species == "versicolor"]
hist(versicolor_length, freq=FALSE)
x <- seq(4, 8, length.out=100)
y <- with(iris, dnorm(x, mean(versicolor_length), sd(versicolor_length)))
lines(x, y, col="red")
lines(density(versicolor_length), col="blue")
legend(1, 95, legend=c("Normal Density", "Kernel Density"), col=c("red",
"blue"), lty=1:2, cex=0.5)
virginica_length <- iris$Sepal.Length[iris$Species == "virginica"]
hist(virginica_length, freq=FALSE)
x <- seq(4, 8, length.out=100)
y <- with(iris, dnorm(x, mean(virginica_length), sd(virginica_length)))
lines(x, y, col="red")
lines(density(virginica_length), col="blue")
legend(1, 95, legend=c("Normal Density", "Kernel Density"), col=c("red",
"blue"), lty=1:2, cex=0.5)
我强烈建议您学习一些整洁的方法,因为它可以使大多数这些问题消失,并且可以使代码更具可读性。
library(tidyverse)
# calculate the normal densities for the three species
x <- seq(4, 8, length.out=100)
iris.norm <- group_by(iris, Species) %>%
summarize(mean = mean(Sepal.Length),
sd = sd(Sepal.Length)) %>%
mutate(data = map2(mean, sd, ~ data.frame(Sepal.Length = x,
density = dnorm(x, .x, .y)))) %>%
unnest()
# plot histograms and densities on top of each other
ggplot(iris) +
geom_histogram(aes(x = Sepal.Length, y = ..density..),
color = "black", fill = "white", bins = 8) +
geom_line(aes(x = Sepal.Length, color = "Kernel Density"),
stat = "density") +
geom_line(data = iris.norm,
aes(x = Sepal.Length, y = density, color = "Normal Density")) +
facet_wrap(~Species, ncol = 1) +
theme_minimal()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.