malinm
malinm

Reputation: 11

Adding a legend for vertical lines of histograms

I'm trying to put a legend for a graph I am creating. The idea is to compare the mean and medians of a skewed and symmetric distribution. This is what I currently have as the code however the

show.legend = TRUE 

code doesn't do the job.

set.seed(19971222)

sym <- as.data.frame(cbind(c(1:500), rchisq(500, df = 2))) # generate 500 random numbers from a symetric distribution
colnames(sym) <- c("index", "rnum")

sym_mean <- mean(sym$rnum)
sym_med <- median(sym$rnum)
# get into a format that tidyverse likes
central_measures <- as.data.frame(cbind(sym_mean, sym_med))
colnames(central_measures) <- c("mean", "median")

sym %>% ggplot(aes(sym$rnum)) + 
  geom_histogram(binwidth = 0.4, fill = "steelblue", colour = "navy", alpha = 0.9) + 
  geom_vline(xintercept = sym_mean, colour = "red", show.legend = TRUE) + 
  geom_vline(xintercept = sym_med, colour = "yellow", show.legend = TRUE) + 
  labs(title = "Histogram of 500 Randomly Generated Numbers from the Chi-Squared Distribution", 
       x = "Value", 
       y = "Frequency") +
  theme_minimal()

I just want to have a legend on the side saying that the red is the "Mean" and the yellow is the "Median".

Thank you!

Upvotes: 1

Views: 1357

Answers (1)

Nate
Nate

Reputation: 10671

Heyyy, sorry I got side-tracked for a bit and my first suggestions was a little off. Here is one way to accomplish your goal of adding a legend for your centrality measures.

# use this instead of central_measures
central_values <- data.frame(measurement = c("mean", "median"),
                             value = c(sym_mean, sym_med))

sym %>% ggplot(aes(sym$rnum)) + 
  geom_histogram(binwidth = 0.4, fill = "steelblue", colour = "navy", alpha = 0.9) + 
  geom_vline(data = central_values, aes(xintercept = value, color = measurement)) +
  scale_color_manual(values = c("red", "orange"), name = NULL) +
  labs(title = "Histogram of 500 Randomly Generated Numbers from the Chi-Squared Distribution", 
       x = "Value", 
       y = "Frequency") +
  theme_minimal()

enter image description here

Let me know if you have any other troubles and sorry again for leading you astray with my comment!

Upvotes: 2

Related Questions