DaniB
DaniB

Reputation: 200

Add the legend to a barplot ggplot

I am working with R and making come charts with ggplot. However, I am trying to add the legend to my barplot through the following code in vain.

library(ggplot2)
library(dplyr)

data<- data.frame(years = c(2009:2018),

                      values <- c(-9400, -8792, -10914, -17996, -25543, -27814, -33335, -38872, -38243, -37034))


my_barplot <- data %>%
  ggplot(aes(x=years, y=values))+
  xlab('name x axis') + ylab('name y axis') +
  geom_col(aes(fill="bla bla"))+
  scale_x_continuous(breaks = seq(2009, 2018, by = 2))+
  labs(title="title", 
       subtitle="Subtitle", 
       caption="Source")+
  geom_text(aes(label=paste0((values))),
            position=position_stack(vjust=0.5),size=3)+
  # scale_color_manual('', labels = 'label', values = 'red') +
  stat_smooth(color = "#FC4E07", fill = "#FC4E07",
    method = "loess",formula = y ~ x, size = 1, se= FALSE)+
  scale_colour_manual(name = 'Legend', 
                      guide = 'legend',
                      values = c('MA50' = 'blue',
                                 'MA200' = 'red'), 
                      labels = c('SMA(50)',
                                 'SMA(200)'))+
  theme_minimal()

Would you be able to help me please?

Upvotes: 1

Views: 416

Answers (1)

stefan
stefan

Reputation: 124413

Try this. BTW I also removed some unnecessary code:

library(ggplot2)
library(dplyr)

data<- data.frame(years = c(2009:2018),
                  values <- c(-9400, -8792, -10914, -17996, -25543, -27814, -33335, -38872, -38243, -37034))


my_barplot <- data %>%
  ggplot(aes(x=years, y=values))+
  xlab('name x axis') + ylab('name y axis') +
  geom_col(aes(fill="label_bar"))+
  scale_x_continuous(breaks = seq(2009, 2018, by = 2))+
  labs(title="title", 
       subtitle="Subtitle", 
       caption="Source")+
  geom_text(aes(label=paste0((values))),
            position=position_stack(vjust=0.5),size=3)+
  # scale_color_manual('', labels = 'label', values = 'red') +
  stat_smooth(aes(color = "label_loess"),
              method = "loess",formula = y ~ x, size = 1, se= FALSE) +
  scale_fill_manual(values = c('label_bar' = 'steelblue')) +
  scale_colour_manual(values = c('label_loess' = 'red',
                                 'SMA(50)' = 'blue',
                                 'SMA(200)' = 'red'))+
  theme_minimal()
my_barplot

Created on 2020-03-23 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions