在scale_x_discrete中使用rev可使条形宽度变小

时间:2019-05-28 19:47:30

标签: r ggplot2

我尝试使用以下代码反转scale_x_discrete中的条形图的顺序:scale_x_discrete("", limits = rev(mt2$cyl))

虽然颠倒了var的顺序,但它也使条的宽度缩小并使它们的间距不相等。我可以考虑这一点,而不必为此担心,但是,我很好奇为什么添加rev(mt2$cyl)会改变条的宽度和间距?

library(dplyr)
library(ggplot2)

mt2 <- mtcars %>% 
  count(cyl, gear) %>% 
  ungroup %>% 
  group_by(cyl) %>% 
  mutate(pct = 100*n/sum(n)) %>% 
  ungroup %>% 
  mutate( gear = as.character(gear),
         cyl = as.character(cyl))

#smaller width 
ggplot(mt2) +
  geom_bar(aes(x=cyl, y=pct, fill=gear),stat = 'identity',width = .9) +
  scale_x_discrete("", limits = rev(mt2$cyl))




#normal width
ggplot(mt2) +
  geom_bar(aes(x=cyl, y=pct, fill=gear),stat = 'identity',width = .9)

enter image description here

enter image description here

0 个答案:

没有答案