Change the default geom_bar to a different default

What i want to do

I currently have a custom theme for my plots and I want to have on top of that some predefined options for all types of plots. My first focus is on histograms, where I want to change the default width.

The default width of the geom_bar in ggplot2 is "Default is 90% data resolution". ( http://ggplot2.tidyverse.org/reference/geom_bar.html ).

I would like to change this default to 75% . To be clear, I am not interested in changing it like this:

geom_bar(stat='identity', width=0.75)

Because that would mean that I have to specify it every time I create a histogram. I want it to become the new default.

What I have tried so far

I tried to change the default width using this:

update_geom_defaults("bar", list(width=0.75))

But then I get an error: Error: Aesthetics must be either length 1 or the same as the data (964): width

. I think it might have to do with the fact that the width is calculated based on the data resolution, which doesn't already exist at the moment when I callupdate_geom_defaults

Also, I also figured out what is width

not part of the default bytes:

GeomBar$default_aes
* colour   -> NA
* fill     -> "grey35"
* size     -> 0.5
* linetype -> 1
* alpha    -> NA

      

My questions:

  • Where is the default 90%?
  • Can you change it in any way?
  • If not, is there any other way to pass a predefined set of parameters to all geom_ * functions?

Thank!

+3


source to share


1 answer


The default is defined in GeomBar

:

GeomBar <- ggproto("GeomBar", GeomRect,
  required_aes = c("x", "y"),

  setup_data = function(data, params) {
    data$width <- data$width %||%
      params$width %||% (resolution(data$x, FALSE) * 0.9)  ## <- right here
    transform(data,
      ymin = pmin(y, 0), ymax = pmax(y, 0),
      xmin = x - width / 2, xmax = x + width / 2, width = NULL
    )
  },

  draw_panel = function(self, data, panel_params, coord, width = NULL) {
    # Hack to ensure that width is detected as a parameter
    ggproto_parent(GeomRect, self)$draw_panel(data, panel_params, coord)
  }
)

      

Award-line use %||%

, which is used to set default values in the event params$width

is NULL

(the default value geom_bar

, NULL

means "to set something reasonable for me '").

There is no good way how update_geom_defaults

to change this. What you can do is make your own geom_bar

like this:



geom_bar75 <- function (..., width = 0.75) {
  geom_bar(..., width = width)
}

      

In most cases this will be very good, i.e. with a discrete x-axis (since the resolution is 1). For more complex cases, you may need to customize or override GeomBar

.

ggplot(mpg, aes(class)) + geom_bar()
ggplot(mpg, aes(class)) + geom_bar75()

      

enter image description here

+3


source







All Articles