DR15
DR15

Reputation: 693

How to remove space in graphics using ggplot

I'm trying to remove some space in my plot, but when I use ylim I got the following warning: Warning message: Removed 2 rows containing missing values (geom_text). Then I lost some data.

Here is my code:

ggplot(data_se5) +
  geom_bar(data=data_se5, aes(x = SEM_PRI, y = acumobito,#color = "Número de internações acumuladas", 
                              fill = CLASSI_FIN,
                              group=CLASSI_FIN),color="transparent",stat="identity") +
  theme(text = element_text(size=20), legend.position="none") +   #re
    annotate("text", x = 1:25, y=cumsum(aggregate(obito ~ SEM_PRI, dadoscovid2, sum)$obito) + 2, 
          vjust = -.8, label = sort(data_se5[data_se5$CLASSI_FIN=="SRAG",]$acumobito), colour = "gold4")+
  annotate("text", x = data_se5[data_se5$CLASSI_FIN=="SRAG-não",]$SEM_PRI, y=data_se5[data_se5$CLASSI_FIN=="SRAG-não",]$acumobito/2-15, 
           vjust = -.8, label = data_se5[data_se5$CLASSI_FIN=="SRAG-não",]$acumobito, colour = "black")+
  scale_x_continuous(breaks = 1:25,labels = labelss) + 
  scale_colour_manual("",values= c("Número de internações acumuladas" = "gold"))+
  scale_fill_manual("","Número de internações acumuladas", values = c("gold","dodgerblue3"))+
  labs(x="Semana Epidemiológica")+ylab("") + theme_bw(base_size = 20)+ylab(NULL)+ylim(-15, max(data_se5$acumtotal)+10)+
  theme(legend.position = "bottom", legend.direction = "horizontal",axis.text.y = element_blank())

And here I paint with red the parts that I'd like to exclude. enter image description here

Any hint on how can I do that?

Upvotes: 1

Views: 350

Answers (1)

stefan
stefan

Reputation: 123768

By default ggplot2 expands the axis for continuous scales by 5 percent on each side and by 0.6 units on each side for discrete scales. To remove or reduce the expansion you can use the expand argument in the scale like so:

library(ggplot2)

# Default
ggplot(mtcars, aes(factor(cyl))) +
  geom_bar()

# Remove expansion
ggplot(mtcars, aes(factor(cyl))) +
  geom_bar() +
  scale_x_discrete(expand = expansion(add = c(0, 0))) +
  scale_y_continuous(expand = expansion(mult = c(0, 0)))

Upvotes: 3

Related Questions