1

I am trying to create a ggplot line graph in R and would like to split the legend into two columns and rename the labels, but so far I have been unable to find a way to do this.

I've found explanations for how to edit legend labels - Editing legend (text) labels in ggplot - and for how to create a multi-column legend - Creating multi column legend in ggplot - but these two solutions do not appear to be compatible as scale_colour_manual appears to create another legend in addition to the guides() legend. My code is as follows:

economy <- read.csv("R input.csv")
economy_melt <- reshape2::melt(economy,id.vars="Time")
my_labels <- c("Baseline Scenario - Value Added - Industry",
               "Volcanic Eruption Scenario - Value Added - Industry",
               "Baseline Scenario - Value Added - Commercial",
               "Volcanic Eruption Scenario - Value Added - Commercial")
my_plot <- ggplot(data = economy_melt, aes(Time, value, colour = variable, linetype = variable)) +
  geom_line(size = 1)
my_plot <- my_plot + theme_bw()
my_plot <- my_plot + theme(legend.direction = "vertical", legend.position = "bottom")
my_plot <- my_plot + guides(col = guide_legend(ncol = 2)) # this line does not appear to work
my_plot <- my_plot + scale_linetype_manual(name=" ",values=c(1,1,1,1), labels = my_labels)
my_plot <- my_plot + scale_color_manual(name = " ",
                                       values=c("#396AB1","#DA7C30","#3E9651","#CC2529"),
                                       labels=my_labels)

my_plot <- my_plot + theme(legend.position = "bottom",
                           legend.title=element_blank(),
                           legend.key = element_rect(fill = "transparent", colour = "transparent"),
                           legend.background = element_rect(fill=alpha('white', 0.8)))
show(my_plot)

The data I'm using is available here

With this code the legend item labels come out correctly but they are in a single column whereas I would like them to be in two columns.

Any assistance would be appreciated.

Please note this is my first StackExchange post - so I am unable to put an image of the graph I get into the query, and apologies if there is something I ought to have done, but haven't.

  • 1
    Can you upload your image of the generated plot somewhere else and post the link here? I'm running into errors replicating your script with the file linked. The data structure is also rather weird... – Adam Quek Jul 31 '19 at 04:47
  • Hi Adam, first please excuse (very) the slow response. I didn't have email notifications turned on so I wasn't aware you had responded. I have edited the data; not sure how to edit the original post; here is a link to the edited data: https://1drv.ms/u/s!AkfPZdxctimVmz08tBsO4jdFN1p7?e=gkyX9t Here is a link to an image of the generated plot: https://1drv.ms/u/s!AkfPZdxctimVmz5I2cXZw4ElK8po?e=gbBYSR Hope that works this time! – Robert Cardwell Feb 27 '20 at 02:50

0 Answers0