无法在ggplot2中创建多个密度图的图例

无法在ggplot2中创建多个密度图的图例

本文介绍了无法在ggplot2中创建多个密度图的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ggplot2绘制了一些有传说的密度图,但我无法将图例添加到最终结果中。

  m <  -  ggplot(chickwts,aes(x = weight))
m + geom_density(kernel =gaussian,adjust = .3,color =green,size = 1)+
geom_density =gaussian,adjust = 1,color =red,size = 1)+
geom_density(kernel =gaussian,adjust = 5,color =blue,size = 1)+
geom_density(内核=高斯,调整= 10,颜色=黄色,大小= 1)+
geom_density(内核=高斯

我已经使用了几个我在这里找到的语法,但没有一个不起作用。
谢谢。

解决方案

ggplot2 美学或传递给 aes()函数的参数。通常,您会指定一个因子作为颜色美学,这会自动创建颜色图例。但是, chickwts 数据集中没有内置密度分组因子,因此您必须制作自己的比例和标签。

不是直接在 geom_density()中定义颜色,您可以定义一个命名的颜色审美,在 scale_colour_manual()中创建的自定义色彩比例如下:

  m m + geom_density(kernel =gaussian,adjust = .3,aes(color =。3),size = 1)+ 
geom_density(kernel =gaussian,adjust = 1,aes(color =1),size = 1)+
geom_density(kernel =gaussian,adjust = 5,aes(color =5 ),size = 1)+
geom_density(kernel =gaussian,adjust = 10,aes(color =10),size = 1)+
geom_density(kernel =gaussian, adjust = 20,aes(color =20),size = 1)+
scale_colour_manual(values = c(。3=green,1=red,5=蓝色,10=黄色,20=橙色),名称=密度)

I am using ggplot2 to have some density plots with legends, but I cannot add legend to my final result.

m <- ggplot(chickwts, aes(x = weight))
m + geom_density(kernel = "gaussian", adjust = .3, colour="green", size=1)+
  geom_density(kernel = "gaussian", adjust = 1, colour="red", size=1)+
  geom_density(kernel = "gaussian",adjust = 5, colour="blue", size=1)+
  geom_density(kernel = "gaussian",adjust = 10, colour="yellow", size=1)+
  geom_density(kernel = "gaussian",adjust = 20, colour="orange", size=1)

I have used several syntaxes which I have found here but none of them did not work.Thank you.

解决方案

ggplot2 bases its legends on aesthetics, or arguments passed to the aes() function. Ordinarily, you'd assign a factor as the color aesthetic, which would create the color legend automatically. However, there is no built-in density grouping factor in the chickwts dataset, so you have to make up your own scale and labels.

Instead of defining the color directly in geom_density(), you can define a named color aesthetic that corresponds to a custom color scale you create in scale_colour_manual(), like so:

m <- ggplot(chickwts, aes(x = weight))
m + geom_density(kernel = "gaussian", adjust = .3, aes(colour=".3"), size=1)+
  geom_density(kernel = "gaussian", adjust = 1, aes(colour="1"), size=1)+
  geom_density(kernel = "gaussian",adjust = 5, aes(colour="5"), size=1)+
  geom_density(kernel = "gaussian",adjust = 10, aes(colour="10"), size=1)+
  geom_density(kernel = "gaussian",adjust = 20, aes(colour="20"), size=1) +
  scale_colour_manual(values=c(".3"="green", "1"="red", "5"="blue", "10"="yellow", "20"="orange"), name="Densities")

这篇关于无法在ggplot2中创建多个密度图的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:01