R:组的颜色的密度图? [英] R: Density plot with colors by group?

查看:331
本文介绍了R:组的颜色的密度图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个人口的数据。
我想在同一图形上获得两者的直方图和密度图。



我试过这个(例子):

 库(ggplot2)
AA < - rnorm(100000,70,20)
BB < - rnorm(100000,120, 20)

valores <-c(AA,BB)
grupo <-c(rep(AA,100000),c(rep(BB,100000)) )
todo< - data.frame(valores,grupo)


ggplot(todo,aes(x = valores,fill = grupo,color = grupo))+
geom_histogram(aes(y = .. density ..),binwidth = 3)+ geom_density(aes(color = grupo))

但我只是得到一个图形与一行和单一的颜色。



我想为两个密度线使用不同的颜色。



我用ggplot2做了,但是base R也可以。



还是我不知道我改变了什么,现在我得到这个:

  ggplot(todo,aes x = valores,fill = grupo,color = grupo)+ 
geom_histogram(position =identity,binwidth = 3,alpha = 0.5)+
geom_density(aes(color = grupo))

,但未绘制密度线。



或甚至奇怪的事情,如



@skan:您的尝试已关闭,但您在直方图中绘制了频率而不是密度值。


I have data from 2 populations. I'd like to get the histogram and density plot of both on the same graphic. With one color for one population and another color for the other one.

I've tried this (example):

library(ggplot2)
AA <- rnorm(100000, 70,20)
BB <- rnorm(100000,120,20)

valores <- c(AA,BB)
grupo <- c(rep("AA", 100000),c(rep("BB", 100000)))
todo <- data.frame(valores, grupo)


ggplot(todo, aes(x=valores, fill=grupo, color=grupo)) +
  geom_histogram(aes(y=..density..), binwidth=3)+  geom_density(aes(color=grupo))

But I'm just getting a graphic with a single line and a single color.

I would like to have different colors for the the two density lines. And if possible the histograms as well.

I've done it with ggplot2 but base R would also be OK.

or I don't know what I've changed and now I get this:

ggplot(todo, aes(x=valores, fill=grupo, color=grupo)) + 
geom_histogram( position="identity", binwidth=3, alpha=0.5)+ 
geom_density(aes(color=grupo))

but the density lines were not plotted.

or even strange things like

解决方案

I suggest this ggplot2 solution:

ggplot(todo, aes(valores, color=grupo)) +
  geom_histogram(position="identity", binwidth=3, aes(y=..density.., fill=grupo),  alpha=0.5) +
  geom_density()

@skan: Your attempt was close but you plotted the frequencies instead of density values in the histogram.

这篇关于R:组的颜色的密度图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆