首页 > 解决方案 > 将图表中的类间隔放在直方图中,例如作为图例

问题描述

我的代码的实际版本是:

hist_Price <- hist(diamonds$price)
hist(x = diamonds$price,
     main = "HIstograma del Precio de los Diamantes (Dataset : diamonds)",
     col="blue",
     ylim = c(0,max(hist_Price$counts)+2000),
     xaxt = 'n' # necesario para el uso de la funcion text()
)
axis(side = 1,at = seq(0,max(diamonds$price),3000))
text(hist_Price$mids,hist_Price$counts,labels=hist_Price$counts, adj=c(0.5, -0.5))
box()

我正在寻找一种将类间隔放在图表中的方法,例如作为图例。也许就像这张图中出现的那样

例子

显然,使用 R 的图形应该看起来更专业

标签: rhistogram

解决方案


您的示例代码需要 19 种不同的颜色。很难区分这么多颜色,所以我将其减少到 10 种。否则只需使用图例功能。

library(ggplot2)    ## for diamonds data
hist_Price = hist(x = diamonds$price,
    breaks = seq(0,20000, 2000),
     main = "Histograma del Precio de los Diamantes (Dataset : diamonds)",
     col=rainbow(10, end=0.85),
     ylim = c(0,max(hist_Price$counts)+2000),
     xaxt = 'n' # necesario para el uso de la funcion text()
)
axis(side = 1,at = seq(0,max(diamonds$price),2000))
text(hist_Price$mids,hist_Price$counts,labels=hist_Price$counts, adj=c(0.5, -0.5))
box()

LABELS = paste(seq(0,18000, 2000), seq(2000,20000, 2000), sep="-")
legend("topright", legend=LABELS, fill=rainbow(10, end=0.85))

带图例的直方图

请注意,我在显示后调整了图像大小。


推荐阅读