3

I like to move the legend a bit further on the left But I am not getting how to do it. Secondly, I also want to reduce the space between axis label and legend too

Can you please suggest something

the code is given below that I am using

The image of the graph is in the link below https://i.stack.imgur.com/GwvkR.jpg

"tooltip"

ggplot(Q6_m, aes( choice,temp,fill=Answer ))+
  geom_bar(position = position_stack(reverse = TRUE), stat="identity") +
  coord_flip() +
  xlab("") +
  ylab("Number of responses") +
  scale_fill_brewer(type = "div") +
  theme(axis.text=element_text(size=8),
        axis.title=element_text(size=8,face="bold"), legend.title = element_blank(),
        legend.text=element_text(size=7)) +
  ggtitle("Q6:Rate your ability to perform the following procedures WITHOUT attending assistance?")+
  theme(plot.title = element_text(color = "black", size = 7.5, face = "bold", hjust = 1))+
  facet_wrap(~gender,scales = "free_x")+
  theme(legend.position="bottom", legend.direction  = "horizontal",legend.key.size = unit(0.5,"line")
        )
camille
  • 16,432
  • 18
  • 38
  • 60
  • 1
    Does this answer your question? [How to move or position a legend in ggplot2](https://stackoverflow.com/questions/2954005/how-to-move-or-position-a-legend-in-ggplot2) – tjebo Apr 02 '20 at 19:56
  • @Tjebo, not sure that the link you are pointing is addressing OP's question as `legend.position = "bottom"` is already place in the code. – dc37 Apr 02 '20 at 22:11
  • @dc37 see this answer to the linked question. https://stackoverflow.com/a/51901724/7941188 The linked question is asked very broadly and should be able to serve as a good source to answer the question from this OP here – tjebo Apr 03 '20 at 12:13
  • 1
    @Tjebo, yes you're right ;). My bad ;) – dc37 Apr 03 '20 at 16:17

1 Answers1

1

You should use legend.justification to get the legend on the left side of the plot and legend.margin to reduce the space between axis labels and the legend:

ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species))+
  geom_boxplot()+
  theme(legend.position = "bottom",
        legend.justification = c(0,1),
        legend.margin = margin(t = -15, r = 0, b = 0, l = 0, unit = "pt"))

enter image description here

Does it answer your question ?

dc37
  • 15,840
  • 4
  • 15
  • 32