顶部的直方图是价格的密度直方图,底部的直方图是克拉的密度(钻石数据集)。
ggplot(diamonds,aes(x=price, fill=color)) +
geom_histogram(aes(y=..density..)) +
theme(legend.position="none") +
theme(axis.title.x=element_blank(), axis.title.y=element_blank())
ggplot(diamonds,aes(x=carat, fill=color)) +
geom_histogram(aes(y =..density..)) +
theme(legend.position = "none") +
theme(axis.title.x=element_blank(), axis.title.y=element_blank())
为什么与上面两张图片不同?怎么做?谢谢!
答案 0 :(得分:1)
ggplot图表尝试根据美学中的变量类型(x,y,fill等)智能地运行。但默认情况下总能做到正确。
在这种情况下,您的x轴有不同的类型: 价格 是一个整数,但 克拉 是数字。 如果要覆盖默认行为,只需使用as.numeric / as.integer / as.factor /等:
ggplot(... aes(x=as.numeric(price), ...
对于价格(整数),默认属性为stat =" bin"。所以你得到堆积直方图。
使用克拉(数字),它是连续的。有关详细信息,请参阅文档。