The objective is to show overlapping histograms, but I want to avoid using the alpha adjustment so that the colours remain bright.
Is there a way to do this without adjusting the alpha arg?
Goal is to display the colors shown below:
hist(rnorm(mean=10, n = 1000), col='blue')
hist(rnorm(mean=11, n = 1000), col='red', add=T)
But also show the overlapping area as shown here
hist(rnorm(mean=10, n = 1000), col='blue')
hist(rnorm(mean=11, n = 1000), col=rgb(1,0,0,0.5), add=T)
Similar question that doesn't quite address transparency:
How to create black and white transparent overlapping histograms using ggplot2?
I'd be fine with densities and use of other graphing packages (e.g. lattice, ggplot2, etc).
Edit: I'd like the plots to be filled and the intersecting area to be a different color (e.g. purple where red and blue intersect).
Plot two histograms Using plot() will simply plot the histogram as if you'd typed hist() from the start. However, you can now use add = TRUE as a parameter, which allows a second histogram to be plotted on the same chart/axis.
To set transparency level, use lessR function set or use rgb function directly. Color of the border of the bars. To set transparency level, use function set or use rgb function directly.
In order to create two histograms on the same plot, similar to the PLOTYY function, you need to create overlapping axes and then plot each histogram on one axis. 1.In order to create overlapping axes, simply create one axes and then create another axes with the same position as the first.
An Overlay Histogram allows you to visualize and compare multiple Populations superimposed on each other.
A solution using ggplot2
and geom_density
.
library(ggplot2)
library(tidyr)
# create data
set.seed(1234)
df <- data.frame(x = rnorm(1000, 10), y = rnorm(1000, 11)) %>%
gather(key, value) # use tidyr::gather to convert from wide to long format
ggplot(df, aes(value, colour = key)) +
geom_density(show.legend = F) +
theme_minimal() +
scale_color_manual(values = c(x = "red", y = "blue"))
# use 'adjust' to adjust density estimation
ggplot(df, aes(value, colour = key)) +
geom_density(show.legend = F, adjust = .5) +
theme_minimal() +
scale_color_manual(values = c(x = "red", y = "blue"))
Since alpha is no option, apart from using densities you could stack the histograms on top of each other, although I'd prefer densities, since they are easier to compare.
# using stacked histograms
ggplot(df, aes(value, fill = key)) +
geom_histogram(show.legend = F) +
theme_minimal() +
scale_fill_manual(values = c(x = "red", y = "blue"))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
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