使用來自 R studio 的 mpg 資料,我想制作一個連接直方圖和密度圖。我使用的代碼是
mpg %>%
ggplot(aes(x = cty))
guides(fill='none')
xlab('Fuel Consumption in City Area')
geom_histogram(aes(y=..density..), binwidth = 50, fill='#3ba7c4')
geom_density(alpha=0.2)
結果是這樣的

因為 Y 軸不再顯示 cty 的計數,所以我想在每個 bin 的頂部放置標簽。我使用的代碼是
mpg %>%
ggplot(aes(x = cty))
guides(fill='none')
xlab('Fuel Consumption in City Area')
geom_histogram(aes(y=..density..), binwidth = 50, fill='#3ba7c4')
stat_bin(binwidth=1, geom='text', color='black', aes(label=..count..), position=position_stack(vjust = 0.5))
geom_density(alpha=0.2)
但是圖形現在只顯示沒有直方圖和密度圖的標簽

如何解決這個問題?
uj5u.com熱心網友回復:
你可以stat = "bin"在里面使用geom_text。用于stat(density)y 軸值和stat(count)美學label。用一個小的負數向上輕推文本vjust,使計數位于條形頂部。
mpg %>%
ggplot(aes(x = cty))
guides(fill = 'none')
xlab('Fuel Consumption in City Area')
geom_histogram(aes(y = stat(density)), binwidth = 50, fill = '#3ba7c4')
geom_text(stat = "bin", aes(y = stat(density), label = stat(count)),
binwidth = 50, vjust = -0.2)
geom_density(alpha = 0.2)

實際上,您會想要更多的箱,并使密度線不那么不透明,這樣它就不會與標簽發生太多沖突。
mpg %>%
ggplot(aes(x = cty))
guides(fill = 'none')
xlab('Fuel Consumption in City Area')
geom_histogram(aes(y = stat(density)), binwidth = 5, fill = '#3ba7c4',
color = '#2898c0')
geom_text(stat = "bin", aes(y = stat(density), label = stat(count)),
binwidth = 5, vjust = -0.2)
geom_density(color = alpha("black", 0.2))
theme_classic()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427650.html
