Means in violin plot not projected properly

Hey guys!

I have the following code:

    ggplot(violin_data_1, aes(x=cpod, y=clx, fill=factor(net_type))) + geom_violin() + ylim(0,100) + 
      ylab("Clicks (n)") + xlab("CPOD ID") + labs(fill = "Net Type") + 
      stat_summary(fun = "mean", geom = "crossbar", width = 0.1, colour = "black")

Which ends up as this plot:

I wonder why all means are projected in the middle violin of each CPOD station? I would like to have one crossbar for each violin.

Thanks in advance. :slight_smile:

I think you need to specify the "position" of your stat_*().


(plt = iris |> 
  pivot_longer(-Species) |> 
  ggplot(aes(x = Species, y = value, color = name)) +

plt + stat_summary(fun = "mean", geom = "crossbar")

plt + stat_summary(fun = "mean", geom = "crossbar", position = position_dodge2())

Created on 2022-01-25 by the reprex package (v2.0.1)

If I add the

position = position_dodge2()

nothing really changes.
Do I need to do the pivot step as well? Maybe you can show me how it has to look with my code?

Thanks for providing code , but you could take further steps to make it more convenient for other forum users to help you.

Share some representative data that will enable your code to run and show the problematic behaviour.

You might use tools such as the library datapasta, or the base function dput() to share a portion of data in code form, i.e. that can be copied from forum and pasted to R session.

1 Like

Since there's no data, wild guesses only. My guess is that @JackDavison is right, but you might need to supply the width of the dodge, e.g.

stat_summary(fun = "mean", geom = "crossbar", position = position_dodge2(width = 0.9))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.