简体   繁体   English

如何在没有数据框的情况下在 ggplot2 中创建直方图?

[英]How to create histogram plot in ggplot2 without data frame?

I am plotting two histograms in R by using the following code.我正在使用以下代码在 R 中绘制两个直方图。

x1<-rnorm(100)
x2<-rnorm(50)  
h1<-hist(x1)
h2<-hist(x2)
plot(h1, col=rgb(0,0,1,.25), xlim=c(-4,4), ylim=c(0,0.6), main="", xlab="Index", ylab="Percent",freq = FALSE)
plot(h2, col=rgb(1,0,0,.25), xlim=c(-4,4), ylim=c(0,0.6), main="", xlab="Index", ylab="Percent",freq = FALSE,add=TRUE)
legend("topright", c("H1", "H2"), fill=c(rgb(0,0,1,.25),rgb(1,0,0,.25)))

The code produces the following output.该代码产生以下输出。 在此处输入图片说明

I need a visually good looking (or stylistic) version of the above plot.我需要上图的视觉上好看(或风格)的版本。 I want to use ggplot2.我想使用 ggplot2。 I am looking for something like this (see Change fill colors section) .我正在寻找这样的东西(请参阅更改填充颜色部分) However, I think, ggplot2 only works with data frames.但是,我认为 ggplot2 仅适用于数据框。 I do not have data frames in this case.在这种情况下我没有数据框。 Hence, how can I create good looking histogram plot in ggplot2?因此,如何在 ggplot2 中创建好看的直方图? Please let me know.请告诉我。 Thanks in advance.提前致谢。

You can (and should) put your data into a data.frame if you want to use ggplot .你可以(也应该)把你的数据变成data.frame ,如果你想使用ggplot Ideally for ggplot , the data.frame should be in long format.理想情况下ggplotdata.frame应该是长格式。 Here's a simple example:这是一个简单的例子:

df1 = rbind(data.frame(grp='x1', x=x1), data.frame(grp='x2', x=x2))

ggplot(df1, aes(x, fill=grp)) + 
  geom_histogram(color='black', alpha=0.5)

There are lots of options to change the appearnce how you like.有很多选项可以改变你喜欢的外观。 If you want to have the histograms stacked or grouped, or shown as percent versus count, or as densities etc., you will find many resources in previous questions showing how to implement each of those options.如果您希望将直方图堆叠或分组,或显示为百分比与计数,或密度等,您会在前面的问题中找到许多资源,这些资源展示了如何实现每个选项。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM