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. 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")
To create multiple histograms in ggplot2, we use ggplot() function and geom_histogram() function of the ggplot2 package. To visualize multiple groups separately we use the fill property of aesthetics function to color the plot by a categorical variable.
In this method, to create a histogram of two variables, the user has to first install and import the ggplot2 package, and then call the geom_histrogram with the specified parameters as per the requirements and needs to create the dataframe with the variable to which we need the histogram in the R programming language.
You have to format your table in long format, then use a long variable as aesthetics in 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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With