I am using ggplot2 and geom_bar() to plot some statistics. Is there a way to customize the fillings in the bar, and the line type for each of the bars? I would like to highlight two key features: There are five bars overall and the numbers they represent are produced from two different types of input, and use three different functions I use for the plot. The bars should show the function, input variation. I thought of using full dark fill for one set of inputs, and white fill for the other set of inputs. For the functions, I could use different line types to show the contrast.
In summary the values from the bar represent outputs from combination of inputs X and Y on functions f1, f2, and f3: bar A: input X function f1; bar B input Y function f1; bar C input X function f2; bar D input Y function f2; bar E input Y function f3.
Any suggestions on how this could be possible? Here is an example I was able to try, but as you see it is not complete to what I want to achieve where I fill subcompact and midsize with a color, but how could I change the line type? and how could I use geom_text() for the text:
library(ggplot2)
data(mpg)
unique(mpg$class)
library(ggplot2)
ggplot(mpg, aes(x = class, fill = class %in% c("subcompact", "midsize"))) +
geom_bar(linetype="dashed", colour="darkgreen") + scale_fill_grey() + guides(fill=FALSE) + theme_classic()
Here is an example with three arbitrary (and arguable) classifications. Note use of dplyr
to define the groups first to make the legends more easily. I am assuming that in most use cases, you would have (or could construct) columns similar to mine here with your data of interest.
I am note sure why you would want to do this for this type of graph, but none the less, it is certainly possible.
Note that I had to muck around with the linetype
legend a little to make it display nicely.
ggplot(mpg %>%
mutate(`Small Car` = class %in% c("subcompact", "midsize")
, `Stuff Hauler` = class %in% c("pickup", "suv")
, `Uncomfortable for long drive` = class %in% c("compact", "pickup", "2seater")
)
, aes(x = class
, fill = `Small Car`
, linetype = `Stuff Hauler`
, col = `Uncomfortable for long drive`
)) +
geom_bar(size = 2) +
scale_fill_grey() +
theme_classic() +
guides(linetype = guide_legend(override.aes = list(fill = NA
, col = "black")))