我正在学习 R,我正在尝试创建一个复合直方图,它将包含三个组的直方图,由数据框中“集群”列的值定义。
数据看起来像这样:
TOTAL_Estimated_Collateral_value_sum cluster
1 -0.17499342 1
2 -0.86443362 1
3 0.22211949 2
4 0.01007717 1
5 -0.77617685 2
6 -1.43518056 1
7 -0.19705983 1
8 -0.39170108 1
9 -0.94073376 1
10 1.20525601 2
TOTAL_Estimated_Collateral_value_sum cluster
Min. :-1.7697 Min. :1.000
1st Qu.:-0.7626 1st Qu.:1.000
Median :-0.1322 Median :1.000
Mean : 0.0000 Mean :1.329
3rd Qu.: 0.8459 3rd Qu.:2.000
Max. : 1.8782 Max. :3.000
> table(df_all$cluster)
1 2 3
24342 8565 1350
我使用的代码如下:
ggplot(df_all, aes(x=TOTAL_Estimated_Collateral_value_sum, color=cluster)) +
geom_histogram(alpha = 0.7, position="dodge")
我得到的图像如下:
如您所见,观察结果并没有像我预期的那样由集群的值着色。
您能否向我解释为什么会这样,以及我应该如何修复我的代码并获得预期的输出?
最佳答案
您需要将 cluster
映射到 fill
,而不是 color
,并且 cluster
需要是一个因素,如果还没有。所以尝试:
ggplot(df_all, aes(x=TOTAL_Estimated_Collateral_value_sum, fill=cluster)) +
geom_histogram(alpha = 0.7, position="dodge")
或者,如果 cluster
不是一个因素:
ggplot(df_all, aes(x=TOTAL_Estimated_Collateral_value_sum, fill=as.factor(cluster))) +
geom_histogram(alpha = 0.7, position="dodge")
关于r - ggplot 不按组对直方图进行着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42886641/