[英]How to plot two histograms on the same axis scale?
我有兩個數據框:dataf1,dataf2。 它們具有相同的結構和列。 3列名稱分別是A,B,C。 他們都有50行。 我想在dataf1和dataf2上繪制B列的直方圖。 我可以分別繪制兩個直方圖,但是它們的比例不同。 我想知道如何將它們放置在使用不同顏色的同一直方圖上,或者繪制兩個相同比例的直方圖?
ggplot() + aes(dataf1$B)+ geom_histogram(binwidth=1, colour="black",fill="white")
ggplot() + aes(dataf2$B)+ geom_histogram(binwidth=1, colour="black", fill="white")
正如Zheyuan所說,您只需要為每個圖設置y限制即可獲得相同的比例尺。 使用ggplot2
,一種方法是使用lims
命令(盡管scale_y_continuous
和coord_cartesian
也可以工作,盡管略有不同)。 您也永遠不要在aes()
使用data$column
。 而是使用data
參數作為數據框和aes()
未引用的列名。 這是帶有一些內置數據的示例。
p1 = ggplot(mtcars, aes(x = mpg)) + geom_histogram() + lims(y = c(0, 13))
p2 = ggplot(iris, aes(x = Sepal.Length)) + geom_histogram() + lims(y = c(0, 13))
gridExtra::grid.arrange(p1, p2, nrow = 1)
兩個在同一圖上得到兩個直方圖,最好的方法是合並數據框。 一個猜測,而沒有看到您的數據是什么樣子:
dataf = rbind(dataf1["B"], dataf2["B"])
dafaf$source = c(rep("f1", nrow(dataf1)), rep("f2", nrow(dataf2))
ggplot(dataf, aes(x = B, fill = source)) +
geom_histogram(position = "identity", alpha = 0.7)
將您的數據合並到一個數據框中,並用新的列來標記數據最初來自哪個數據幀。 然后,使用該新列填充圖塊的填充美學效果。
data1$source="Data 1"
data2$source="Data 2"
dat_combined = rbind(data1, data2)
您尚未提供示例數據,因此這里有一些使用內置iris
數據框的可能繪圖示例。 在下面的圖中, dat
類似於dat_combined
, Petal.Width
類似於B
, Species
類似於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 ~ .)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.