0

I am struggling with generating a legend and its labels for my ggplot + geom_point.

The following is my code

# Create an index to hold values of m from 1 to 100
m_index <- (1:100)

# Creating data frames to store the correlations
data_frame_50 <- data.frame(prob_max_abs_cor_50)
data_frame_20 <- data.frame(prob_max_abs_cor_20)


library(ggplot2)




# Plot correlations using ggplot and geom_point 
ggplot() +
geom_point(data = data_frame_50, aes(x = m_index, y  = prob_max_abs_cor_50),  
 colour = 'red') +
geom_point(data = data_frame_20, aes(x = m_index, y = prob_max_abs_cor_20),
 colour = 'blue') +
labs(x = " Values of m  ", y = " Maximum Absolute Correlation ",
 title = "Dot plot of probability")

enter image description here

MY.BK
  • 167
  • 1
  • 2
  • 12
  • 3
    Possible duplicate of [R - ggplot line color (using geom\_line) doesn't change](https://stackoverflow.com/questions/48051905/r-ggplot-line-color-using-geom-line-doesnt-change) – Richard Telford Feb 03 '19 at 15:07
  • I have tried running the code according to the link above but there is no change, instead the legend box disappeared – MY.BK Feb 03 '19 at 15:24
  • 1
    As others have stated, this is covered elsewhere. `ggplot2` works better if your data is in a single, long data frame. In your case, try:`df <- data.frame(m_index, prob_max_abs_cor_20, prob_max_abs_cor_50); df_long <- gather(df, type, value, -m_index); ggplot(df_long, aes(x = m_index, y = value, colour = type)) + geom_point() + labs(x = "Values of m", y = " Maximum Absolute Correlation ", title = "Dot plot of probability")` – Nick Kennedy Feb 04 '19 at 00:17
  • Yes the legend has appeared. how about renaming the legend labels? I changed type to legend and the labels at the side read prob_max_abs_cor_20 and prob_max_abs_cor_50. i would like to change it to n = 20 and n = 50 respectively – MY.BK Feb 04 '19 at 03:01

0 Answers0