最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

r - adjust bar width, padding, and distance between x categories INDEPENDENTLY in 2 factor ggplot - Stack Overflow

programmeradmin3浏览0评论

I am trying to create a 2-factor plot where I can increase the distance between categories (dog vs. cat) WITHOUT affecting the padding between bars or width of the bars. This has been a whack-a-mole game -- I only seem to be able to change this distance by decreasing the width of the bar or padding, which I don't want to do. Any help is much appreciated. Reprex below...

sex <- c('f','m','f','m')
pet <- c('cat', 'cat', 'dog', 'dog')
mean <- c(4, 5, 4, 5)

df <- data.frame(sex, pet, mean) 

ggplot(data = df, aes(x = pet, y = mean, fill = sex)) +
  geom_bar(stat = 'identity',
           position = position_dodge2(preserve = "single", 
                                      padding = 0.2),  width = 1)  

I am trying to create a 2-factor plot where I can increase the distance between categories (dog vs. cat) WITHOUT affecting the padding between bars or width of the bars. This has been a whack-a-mole game -- I only seem to be able to change this distance by decreasing the width of the bar or padding, which I don't want to do. Any help is much appreciated. Reprex below...

sex <- c('f','m','f','m')
pet <- c('cat', 'cat', 'dog', 'dog')
mean <- c(4, 5, 4, 5)

df <- data.frame(sex, pet, mean) 

ggplot(data = df, aes(x = pet, y = mean, fill = sex)) +
  geom_bar(stat = 'identity',
           position = position_dodge2(preserve = "single", 
                                      padding = 0.2),  width = 1)  
Share Improve this question edited Mar 16 at 16:48 stefan 127k6 gold badges38 silver badges76 bronze badges Recognized by R Language Collective asked Mar 16 at 15:44 wythe4wythe4 1391 silver badge9 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

One option would be to use ggh4x package which via scale_x_manual allows to manually set the positions for the categories, i.e. whereas the ggplot2 will by default position the catgeories at 1, 2, ... we can shift the first category slightly to the left and the second slightly to the right, thereby increasing the space between categories:

library(ggplot2)
library(ggh4x)

ggplot(data = df, aes(x = pet, y = mean, fill = sex)) +
  geom_bar(
    stat = "identity",
    position = position_dodge2(
      preserve = "single",
      padding = 0.2
    ), width = 1
  ) +
  ggh4x::scale_x_manual(
    values = c(.9, 2.1),
    c_limits = c(.9, 2.1)
  )

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论