[英]R ggplot: Two histograms (based on two different column) in one graph
I want to put two histograms together in one graph, but each of the histogram is based on different column. 我想在一个图中将两个直方图放在一起,但每个直方图都基于不同的列。 Currently I can do it like this, But the position=dodge does not work here.
目前我可以这样做,但position = dodge在这里不起作用。 And there is no legend (different color for different column).
并且没有传说(不同列的颜色不同)。
p <- ggplot(data = temp2.11)
p <- p+ geom_histogram(aes(x = diff84, y=(..count..)/sum(..count..)),
alpha=0.3, fill ="red",binwidth=2,position="dodge")
p <- p+ geom_histogram(aes(x = diff08, y=(..count..)/sum(..count..)),
alpha=0.3,, fill ="green",binwidth=2,position="dodge")
You have to format your table in long format, then use a long variable as aesthetics in ggplot. 你必须以长格式格式化表格,然后在ggplot中使用长变量作为美学。 Using the iris data set as example...
以虹膜数据集为例......
data(iris)
# your method
library(ggplot2)
ggplot(data = iris) +
geom_histogram(aes(x = Sepal.Length, y=(..count..)/sum(..count..)),
alpha=0.3, fill ="red",binwidth=2,position="dodge") +
geom_histogram(aes(x = Sepal.Width, y=(..count..)/sum(..count..)),
alpha=0.3,, fill ="green",binwidth=2,position="dodge")
# long-format method
library(reshape2)
iris2 = melt(iris[,1:2])
ggplot(data = iris2) +
geom_histogram(aes(x = value, y=(..count..)/sum(..count..), fill=variable),
alpha=0.3, binwidth=2, position="identity")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.