1

I would like to put legends in my histogram without overlapping lines. I am going to show my R codes, and the histogram.

#Installing 'readxl' to load a xlsx file    
install.packages("readxl")
library(readxl)

#Loading xlsx file
value <- read_excel("C:/Users/user/Desktop/value.xlsx")

#Setting 'graph' vector
graph <- hist(value$value)

#Calculating 'frequency percentage'
graph$density <- graph$counts / sum(graph$counts) * 100

#Drawing a histogram
plot(graph, main = "Title", xlab = "x-axis", ylab = "Frequency(%)", ylim = c(0, 100), breaks = "Sturges", col = "Gray", freq = FALSE, xaxt = "n")
axis(side = 1, at = seq(-8, 8, by =2))

#Plotting a frequency(%) polygon on the histogram(I have no idea how to draw smooth curve; thus, I used 'line() function')
lines(x = graph$mids, y =graph$density, type = "l", lty = 6, col = "Red")

#Putting a legend on the topright of the graph
legend("topright", c("The distribution of frequency(%)", "mean", "±2SD"), col = c("Red", "Black", "Black"), lty = c(6, 1, 2), lwd = c(2, 1, 1))

#Computing mean and standard deviations
m <- mean(value$value)
std <- sd(value$value)

#Plotting mean and ±2SD values
abline(v = m, lty = 1)
abline(v = m + 2*std, lty = 2)
abline(v = m - 2*std, lty = 2)

By the way, the legend is overlapped on the histogram. This is the picture of the result of the R codes. enter image description here

Could I put legends another area, which is not overlapped with the graph? I need your help, and thank you so much.

seulki choi
  • 45
  • 1
  • 8

1 Answers1

1

It depends on where you want the legend to appear. Here is one example where it's on the right side of the title:

value <- rnorm(1000)
graph <- hist(value, breaks="Sturges", main = "Title", xlab = "x-axis", ylab = "Frequency(%)", col = "Gray", freq = FALSE, xaxt = "n")
axis(side = 1, at = seq(-8, 8, by =2))

#Plotting a frequency(%) polygon on the histogram(I have no idea how to draw smooth curve; thus, I used 'line() function')
lines(x = graph$mids, y = graph$density, type = "l", lty = 6, col = "Red")

#Putting a legend on the topright of the graph
legend("bottomright", c("The distribution of frequency(%)", "mean", "±2SD"),
       col = c("Red", "Black", "Black"), lty = c(6, 1, 2), lwd = c(2, 1, 1),
       xpd=TRUE, inset=c(0,1), cex=0.7, bty='n'
       )

#Computing mean and standard deviations
m   <- mean(value)
std <- sd(value)

#Plotting mean and ±2SD values
abline(v = m + c(0, 2*std, -2*std), lty=c(1,2,2))

Note that I only added xpd, inset, cex and bty parameters to the legend. first two are most important: xpd allows you to plot the legend outside the plotting region in the margins and inset controls the adjustment of legend position. You can learn more about these in help(legend).

Here is the resulting plot:

barplot with legend

You can see more examples and explanations here: Plot a legend outside of the plotting area in base graphics?

Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89