Suppose a violin plot created using ggplot2 with only one factor (on the horizontal axis). This plot shows colorless violins as the single factor is used for the x-axis.
For example, this quick MWE:
oneplot <- ggplot(ToothGrowth, aes(x=dose, y=len))
geom_violin()
oneplot
Is it possible afterwards to set the fill colours? In my actual setting, the plot is generated through a large procedure in charge of multiple things and it does not assign a "fill" aesthetics; it just delivers a plot that can be changed post-hod with additional graphic directives such as scale_fill_manual
.
I was hoping that I could add some directives, e.g.,
oneplot scale_fill_manual(breaks = c(0.5,1,2), values = c("orange", "purple","blue"))
but for the moment, the fillings stay utterly colorless!
CodePudding user response:
Not very well known, but you can use aes
as an additive plot component too.
So:
oneplot <- ggplot(ToothGrowth, aes(x=factor(dose), y=len))
geom_violin()
oneplot
oneplot aes(fill = supp)
This does assume that your fill variable is present in the data, so supp
must be present in ToothGrowth
. However, we can update the data component too, using the special operater % %
:
oneplot % % filter(ToothGrowth, dose < 2) aes(fill = supp)
These techniques can be very useful when making slight variations of the same plot. Define the large structure once, then update the data or aesthetics for each plot.
CodePudding user response:
I think the specific result you were looking for (which is really just a follow-on from Axeman's answer) is:
oneplot
aes(fill = factor(dose))
scale_fill_manual(breaks = c(0.5,1,2), values = c("orange", "purple","blue"))