Combination of stacked and side-by-side bar charts in R - r

In the lattice package of R it is possible to create stacked bar charts. I would like to have several stacked bars side by side similar to this one:
barchart( mpg ~ as.factor(gear), data=mtcars, groups=cyl, stack=F, horizontal=F, auto.key=T )
This is almost what I need. The problem is that the bars are layered, e.g. for the pink bar at the center there are 3 layered bars of approximately the same value (between 17 and 22). The bars are not stacked. The bar that is painted later covers bars painted earlier.
Would it also be possible to have different colors/textures for the stacked bars as well as for the side-by-side bars and an additional legend? The different levels in the stack come from an additional factor.

library(ggplot2)
ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) + geom_bar(stat = "identity", colour = "black") + facet_wrap(~gear)
mtcars$ID <- rownames(mtcars)
ggplot(mtcars, aes(x = factor(gear), y = mpg, fill = factor(cyl), group = ID)) + geom_bar(stat = "identity", position = "dodge")
ggplot(mtcars, aes(x = factor(gear), y = mpg, colour = factor(cyl))) + geom_jitter()
ggplot(mtcars, aes(x = factor(gear), y = mpg, colour = factor(cyl))) + geom_boxplot()

Related

how to add legends ggplot in charts facet_warp() in R?

I maked the chart in R using gglopt() and facet_warp(), but do not appear legends of geom_lines() and stat_smooth().
my code exemple is:
p <- ggplot(data = mtcars, aes(x = hp, y = disp)) +
geom_line(color="red")+
facet_wrap(~cyl)+
stat_smooth()+
guides()
how to add legends in the chart final?
You can add the labels for color aesthetics for each plot and link the color using named vectors in values parameter of scale_color_manual().
ggplot(data = mtcars, aes(x = hp, y = disp)) +
geom_line(aes(color = "line.color")) +
stat_smooth(aes(color = "smooth.color")) +
facet_wrap(~cyl) +
scale_color_manual(name = "", values = c("line.color" = "red", "smooth.color" = "blue"))

Single colored barchart

I have currently tried a course and would like to replicate it on my r-studio however, why can I only show a single color bar plot provided the code below? Is it related to the base color of the fill function? Thanks!
head(mtcars)
library(ggplot2)
# Bar chart
ggplot(mtcars, aes(x = cyl, fill = am)) +
geom_bar(position = "fill")
# Convert bar chart to pie chart
ggplot(mtcars, aes(x = factor(1), fill = am)) +
geom_bar(position = "fill") +
facet_grid(. ~ cyl) + # Facets
coord_polar(theta = "y") + # Coordinates
theme_void() # theme
Welcome to SO! I think you only need to add the group option to the aes():
ggplot(mtcars, aes(x = cyl, fill = am, group = am)) + geom_bar(position = "fill")
But maybe in this way it could be more readable:
ggplot(mtcars, aes(x = as.factor(cyl), fill = as.factor(am), group = as.factor(am))) +
geom_bar(position = "fill") +
xlab("CYL") + # change x axis label
labs(fill = "am") # change legend title

ggplot Adding Tracking Colors Below X-Axis

I'd like to add a line below the x-axis where its color is dependant on a factor that is not plotted.
In this example, I'm creating a box plot and would like to add a line that indicates another variable.
Using the cars data set as an example and then physically dawing in what I'm trying to do:
ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) +
geom_boxplot()
My thought was to create a bar, column, or geom_tile plot and then arrange it below the boxplot. This is how I would do it in base R. Is there a way to add in these kinds of color labels in ggplot2?
The natural way in ggplot2 to do this sort of thing would to be facet on the categorical variable to create subplots. However if you want to keep everything on the same graph you could try using a geom_tile() layer something like this:
df <-data.frame(x = factor(c(4,6,8)), colour = factor(c(1,2,1)))
ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) +
geom_boxplot() +
geom_tile(data=df, aes(x = x, y = 8, fill = colour))
Alternatively as you suggest you could align an additional plot underneath it. You could use ggarrange() in the ggpubr package for this:
plot1 <- ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) +
geom_boxplot() +
geom_tile(data=df, aes(x = x, y = 10, fill = colour))
theme(legend.position = 'none')
plot2 <- ggplot(df, aes(x=x, y=1, fill = colour)) +
geom_tile() +
theme_void() +
scale_fill_manual(values=c('orange', 'green', 'orange')) +
theme(legend.position = 'none')
library(ggpubr)
ggarrange(plot1, plot2, nrow = 2, heights = c(10, 1), align = 'h')

control hierarchy of position_dodge

Is there a way to control which element is plotted in front of the other if one uses dodged bar charts.
ggplot(mtcars, aes(x=factor(cyl), fill=factor(vs))) +
geom_bar(position= position_dodge (width = - 0.5))
In this example the blue bars are plotted in front of the red ones. Is it possiple to reverse the order without hacking alpha values?
Your control here is limited. Using factor levels we can control i) the fill color ordering and ii) the ordering of position_dodge using group.
Here are the four options:
p1 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 0:1), group = factor(vs, 0:1))) +
geom_bar(position = position_dodge(width = - 0.5))
p2 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 0:1), group = factor(vs, 1:0))) +
geom_bar(position = position_dodge(width = - 0.5))
p3 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 1:0), group = factor(vs, 0:1))) +
geom_bar(position = position_dodge(width = - 0.5))
p4 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 1:0), group = factor(vs, 1:0))) +
geom_bar(position = position_dodge(width = - 0.5))
library(cowplot)
plot_grid(p1, p2, p3, p4, align = 'hv')
So it seems only the dodging order is important. In the dev version at least, the right bar is always plotted in front of the left bar.

Plot multiple group histogram with overlaid line ggplot

I'm trying to plot a multiple group histogram with overlaid line, but I cannot get the right scaling for the histogram.
For example:
ggplot() + geom_histogram(data=df8,aes(x=log(Y),y=..density..),binwidth=0.15,colour='black') +
geom_line(data = as.data.frame(pdf8), aes(y=pdf8$f,x=pdf8$x), col = "black",size=1)+theme_bw()
produces the right scale. But when I try to perform fill according to groups, each group is scaled separately.
ggplot() + geom_histogram(data=df8,aes(x=log(Y),fill=vec8,y=..density..),binwidth=0.15,colour='black') +
geom_line(data = as.data.frame(pdf8), aes(y=pdf8$f,x=pdf8$x), col = "black",size=1)+theme_bw()
How would I scale it so that a black line is overlaid over the histogram and on the y axis is density?
It is going to be difficult for others to help you without a reproducible example, but perhaps something like this is what you're after:
library(ggplot2)
ggplot(data = mtcars, aes(x = mpg, fill = factor(cyl))) +
geom_histogram(aes(y = ..density..)) +
geom_line(stat = "density")
If you would rather the density line pertain to the entire dataset, you need to move the fill aesthetic into the geom_histogram function:
ggplot(data = mtcars, aes(x = mpg)) +
geom_histogram(aes(y = ..density.., fill = factor(cyl))) +
geom_line(data = mtcars, stat = "density")

Resources