使图例不与R中的直方图重叠

时间:2018-03-28 07:46:34

标签: r plot histogram legend distribution

我想在我的直方图中添加图例而不重叠线条。 我将展示我的R代码和直方图。

#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)

顺便说一下,图例在直方图上重叠。这是R代码结果的图片。 enter image description here

我可以将图例放在另一个与图表不重叠的区域吗? 我需要你的帮助,非常感谢你。

1 个答案:

答案 0 :(得分:1)

这取决于您希望图例显示的位置。这是一个例子,它位于标题的右侧:

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))

请注意,我只在图例中添加了xpdinsetcexbty参数。前两个是最重要的:xpd允许您在边距内绘制绘图区域外的图例,inset控制图例位置的调整。您可以在help(legend)中了解有关这些内容的更多信息。

以下是结果图:

barplot with legend

您可以在此处查看更多示例和说明:Plot a legend outside of the plotting area in base graphics?