R图中的图例有核密度,正常密度和直方图?

时间:2018-01-21 05:17:06

标签: r plot histogram kernel-density density-plot

我目前是R的初学者,并且有一个关于如何为我正在处理的三个地块插入图例的问题。我正在使用R上的内置数据集iris。为了让传说出现,我觉得应该有所作为,但事实并非如此,因为只有情节出现。我附上了下面的图片。有人可以告诉我我需要做什么才能让传奇出现在各自的情节中吗?先感谢您。

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)

1 个答案:

答案 0 :(得分:0)

我强烈建议学习一些tidyverse,因为它会使大部分问题消失,并且会导致代码更易读。

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()

enter image description here