Save a legend to a Boxplot with ggsave

215 Views Asked by At

I'm pretty new to R and have a question regarding ggsave. I use the following code to first create a box plot, then add a bee swarm plot on top of it and save it with ggsave. Now, I would like to add a p-value on the bottom of the plot. However, I don't know how to include it in the script for it to be saved. I tried adding "+" or "," but it never showed in the output pdf. Maybe you can help me? That would be great, thanks! :) Tobey

ggsave(filename="test.pdf", plot=print(
    boxplot(X ~ Y, data = df, 
            main = 'title',
            add=FALSE,
            ) +
    beeswarm(X ~ Y, data = df, method="hex",
              corral="random",
              add = TRUE)
            ),
scale=1.5,
dpi=300,
width=10, height=10,
units="cm")

I would now like to add the following legend with the legend() function.

legend("bottom",legend="p=0.014")
1

There are 1 best solutions below

0
On

Try:

ggsave(filename="test.pdf", plot=print(
  beeswarm(X ~ Y, data = df, method="hex",
           corral="random",
           add = F),legend("bottom",legend="p=0.014") +
    boxplot(X ~ Y, data = df, 
            add=T)
),
scale=1.5,
dpi=300,
width=10, height=10,
units="cm",
)

Tip for posting in SO: If possible share a sample of your data or simply use dput(df), where df is your dataset.