controling bar length in ggplot

Viewed 21

I want to use the below in rmarkdown word document but the bars are too long; the axis break is good. I want to compress the size of ggplot bars while maintaining readiblity

library(tidyverse)
library(scales)
library(patchwork)
options(scipen = 999)

df <- tribble(
  
  ~category, ~ numbers, ~value,
  
  "category 1",8,   9901020,
  
  "category 2",8    ,18629623,
  
  "category 3",9    ,16471680,
  
  "category 4",7    ,13661732,
  
  "category 5",5    ,7173011,
  
  "category 6",10,  18395574)





dfmod <-  df%>%
  dplyr::mutate(numbers_lable= numbers
                ,numbers = numbers * 1e6) 


pl <- ggplot(data = dfmod,aes(x= fct_reorder(category,desc(value))
                              , y = value))
pl <- pl +  geom_col(fill = "grey")  
pl <- pl + geom_line(aes(y =  numbers, group = 1), size = .8, color = "blue") 
pl <- pl +  geom_text(aes(label =  paste0('Sales' 
                                          , scales::comma(value)
                                          , '\n(Orders '
                                          , numbers_lable,')'))
                      , vjust  = -0.3
                      , size = 3) 

pl <- pl + scale_y_continuous(name= "Sales revenue"
                              ,labels = scales::comma_format(scale = 1e-6
                                                             ,suffix = "M")
                              , sec.axis = sec_axis( trans= ~./1e6
                                                     , name = "Number of sales"
                                                     , breaks = c(0,2,4,6,8,10)))
pl <- pl + theme_bw()
pl <- pl + theme(axis.title.y = element_text(color = "grey")
                 ,axis.title.y.right = element_text(color = "blue")
)

pl

tried fig.width/height, out.width/height whenever I change them they just chop the labels

in excel I would size the chart for example as 12 cm * 5 cm and everything would be visible but with smaller space

1 Answers

Extend the upper limit of your y-axis, e.g.,

sec.axis = sec_axis(
  trans= ~./1e6,
  name = "Number of sales",
  breaks = c(0, 2, 4, 6, 8, 10)), 
  limits = c(0, max(df$value) * 1.2)
)

Use fig.width/fig.height for output-dependent adjustment. The following looks fine for PDF output

```{r, echo=F, fig.width=8, fig.height=4}
<your figure code>
```

enter image description here

Related