ggplot with custom legend

I would like to add a legend to a ggplot2. The dataframe has many categorical variables that are easily transformable into numbers (they are on a Likert scale). I am trying to display the data with a stat_count().

ggplot(results,aes(as.numeric(results[,x]), fill =results[,x]))+
stat_count(aes(y = stat(count) / sum(count)), show.legend = TRUE)+
geom_text(aes(label = round(stat(count) / sum(count),3), y= stat(count) / sum(count)), stat= "count", vjust = -.25) +
xlim(c(0,5)) +
geom_vline(xintercept = mx, colour = "red", lwd = 2, lty=3) +
labs(title = title) +
xlab(paste0("Your average for this question is: ", mx))+
ylab("")

The ylim needs to be from 0.0 to 1.0.
This is a screenshot of what I would like to achieve, but instead of col I would like to put Legend, I need a color for each number 1 2 3 4 5 although 3, 4 and 5 do not appear. And they to be ordered one under another.

Hi Dan,

In order to help you better, it would help us a lot of you can provide a minimal reproducible example.


library(tidyverse)
results <- factor(x=c(rep("1",6),rep("2",3)),
                     levels = as.character(0:5)) %>% 
                enframe(value="xaxis",
                         name="entry")
mx <-1.5

title <- "some title"

ggplot(results,aes(x=xaxis, fill =xaxis))+
  stat_count(aes(y = stat(count) / sum(count)), show.legend = TRUE) +
  scale_fill_discrete(drop=FALSE,name="title I want") + 
  scale_x_discrete(drop=FALSE) +
  geom_text(aes(label = round(stat(count) / sum(count),3),
                y= stat(count) / sum(count)), stat= "count", vjust = -.25) +
  ylim(c(0,1))+
  geom_vline(xintercept = mx, colour = "red", lwd = 2, lty=3) +
  labs(title = title) +
  xlab(paste0("Your average for this question is: ", mx))+
  ylab("")
1 Like

Awesome, thank you, I will check this solution to see if it works with my dataset, so I will dig into it and come back with the final result.

Super, did work like a charm. I have an extra question, what if I wanted to define the colors on my own? Would

scale_fill_manual

do the trick?

yes indeed, scale_fill_manual

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.