如何在同一轴刻度上绘制两个直方图? [英] How to plot two histograms on the same axis scale?

查看:58
本文介绍了如何在同一轴刻度上绘制两个直方图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据帧:dataf1,dataf2.它们具有相同的结构和列.3列名称分别是A,B,C.他们都有50行.我想在dataf1和dataf2上绘制B列的直方图.我可以分别绘制两个直方图,但是它们的比例不同.我想知道如何使用不同的颜色将它们放在相同的直方图上,或者绘制两个相同比例的直方图?

I have two dataframes: dataf1, dataf2. They have the same structure and columns. 3 columns names are A,B,C. And they both have 50 rows. I would like to plot the histogram of column B on dataf1 and dataf2. I can plot two histograms separately but they are not of the same scale. I would like to know how to either put them on the same histogram using different colors or plot two histograms of the same scale?

ggplot() + aes(dataf1$B)+ geom_histogram(binwidth=1, colour="black",fill="white") 
ggplot() + aes(dataf2$B)+ geom_histogram(binwidth=1, colour="black", fill="white")

推荐答案

将数据组合到一个数据框中,并用新的列来标记数据最初来自哪个数据框.然后,使用该新列来填充图块的填充美学效果.

Combine your data into a single data frame with a new column marking which data frame the data originally came from. Then use that new column for the fill aesthetic for your plot.

data1$source="Data 1"
data2$source="Data 2"

dat_combined = rbind(data1, data2)

您尚未提供示例数据,因此以下是一些使用内置 iris 数据框的可能绘图的示例.在下面的图中, dat 类似于 dat_combined Petal.Width 类似于 B Species 类似于 source .

You haven't provided sample data, so here are a few examples of possible plots, using the built-in iris data frame. In the plots below, dat is analogous to dat_combined, Petal.Width is analogous to B, and Species is analogous to source.

dat = subset(iris, Species != "setosa") # We want just two species

ggplot(dat, aes(Petal.Width, fill=Species)) + 
  geom_histogram(position="identity", colour="grey40", alpha=0.5, binwidth=0.1)

ggplot(dat, aes(Petal.Width, fill=Species)) + 
  geom_histogram(position="dodge", binwidth=0.1)

ggplot(dat, aes(Petal.Width, fill=Species)) + 
  geom_histogram(position="identity", colour="grey40", binwidth=0.1) +
  facet_grid(Species ~ .)

这篇关于如何在同一轴刻度上绘制两个直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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