Marty
Marty

Reputation: 85

Legend format and placement using barplot in R

I would like to place the legend of my bar chart beneath the x axis and have it horizontally spread out landscape across the bottom of the chart if possible.

As things stand my chart looks like this

My data is as follows

dput(counts)

structure(c(11L, 3L, 7L, 4L, 12L, 4L, 5L, 4L), .Dim = c(4L, 2L
), .Dimnames = list(as.numeric.Final_DF.web_browser. = c("1", 
"2", "3", "4"), g = c("1", "2")), class = "table")

counts
                                g
as.numeric.Final_DF.web_browser.  1  2
                               1 11 12
                               2  3  4
                               3  7  5
                               4  4  4

My code looks like

barplot(counts, names.arg=c("male", "female"),
        main = "Browser used during purchase",
        col = c("lightblue", "mistyrose", "lavender", "lightcoral"),
        ylab = "Count",
        beside = TRUE,
        legend.text = c("chrome", "internet explorer", "firefox", "netscape"),
        args.legend = list(x = 10, y = 10))  

Any ideas please?

Upvotes: 3

Views: 1767

Answers (2)

Duck
Duck

Reputation: 39613

In ggplot2:

library(tidyverse)
#Code
counts %>% as.data.frame.matrix %>%
  rownames_to_column('Var') %>%
  pivot_longer(-Var) %>%
  mutate(name=ifelse(name==1,'male','female'),
         name=factor(name,levels = unique(name),ordered = T))%>%
  ggplot(aes(x=factor(Var),y=value,fill=Var))+
  geom_bar(stat = 'identity')+
  scale_x_discrete(labels=c("","","",""))+
  scale_fill_manual(values=c("lightblue", "mistyrose",
                             "lavender", "lightcoral"),
                    labels=c("chrome", "internet explorer",
                             "firefox", "netscape"))+
  facet_wrap(.~name,strip.position = 'bottom')+
  theme_bw()+
  theme(strip.placement = 'outside',
        strip.background = element_blank(),
        legend.position = 'bottom',
        axis.ticks.x =  element_blank(),
        plot.title = element_text(hjust=0.5))+
  labs(x='')+
  ggtitle("Browser used during purchase")

Output:

enter image description here

Upvotes: 1

G5W
G5W

Reputation: 37661

You can do that by adding the additional argument to legend: horiz=T and then adjusting the position.

barplot(counts, names.arg=c("male", "female"),
        main = "Browser used during purchase",
        col = c("lightblue", "mistyrose", "lavender", "lightcoral"),
        ylab = "Count",
        beside = TRUE,
        legend.text = c("chrome", "internet explorer", "firefox", "netscape"),
        args.legend = list(x = 9, y = -1.9, horiz=T))  

Repositioned legend

Upvotes: 5

Related Questions