0

I would like my legend to be in this order: Positive, Neither, Negative, Cannot_Say. Additionally, I'm having difficulties moving it vertically closer and horizontally centered to the chart itself.

Here is my code:

#Load libraries
library(tidyverse)
library(ggplot2)

#Set working directory
setwd("~/Documents/Folder/")

#Create dataframe
dat <- data.frame(Film = c("The Road", "Cloverfield", "A Quiet Place"), Positive = c(6, 4, 6), Neither = c(21, 9, 13), Negative = c(54, 74, 69), Cannot_Say = c(19, 13, 12))
dat$Film <- factor(dat$Film, levels = c("A Quiet Place", "Cloverfield", "The Road"))

#Generate stacked bar chart
dat %>% 
  gather(Opinion, value, -Film) %>%
  ggplot(aes(x = Film, y = value, group = Opinion, fill = Opinion)) + coord_flip() +

  #Adjust the bar width
  geom_bar(stat = "identity", width = 0.75) + theme(panel.background = element_blank()) +

  #Establish chart attributes
  ggtitle("Opinion of Post-Apocalyptic Films") + xlab("") + ylab("") +
  theme(plot.title = element_text(face = "bold", family = "Open Sans", size = "14")) +
  theme(plot.title = element_text(vjust = -0.25)) + 
  theme(plot.title = element_text(hjust = -0.4)) + 
  theme(axis.ticks = element_blank()) +
  theme(axis.text = element_text(size = 12, color = "black", family = "Open Sans")) +

  #Set colors
  scale_fill_manual(values=c("#0A2240", "#981B1E", "#C1A783", "#008000")) +

  #Adjust legend
  theme(legend.position="bottom") +
  theme(legend.title = element_blank()) +
  theme(legend.text = element_text(size = 10)) +
  theme(legend.spacing.x = unit(0.25, "inches")) +

  #Center the plot title
  theme(axis.text.y = element_text(margin = margin(r = -10))) + 
  scale_y_continuous(labels = function(x) paste0(x, "%")) +

  #Remove y-axis label and tick marks
  theme(axis.title.y=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.y=element_blank())

I'm getting the following graphic:

Opinion of Post-Apocalyptic Films

  • 2
    Welcome to Stack Overflow! You should provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). We don't have access to your *Documents* folder. Cheers. – M-- Jan 22 '20 at 18:07
  • 1
    Maybe use `theme(legend.margin=unit(-.05,"cm"))`. – M-- Jan 22 '20 at 18:09

1 Answers1

0

I belive that there is no way per se to move it closer, you can change the position or alternatively change the size of the legend to make it larger in a sense bringing it closer to the plot. Alternatively you can position the legend in the plot using p + theme(legend.position = c(0.8, 0.2))

p being your base plot code, colour etc.